105

If I have an Activity class called TestActivity in my application, is there a way to get its class by its name like in this example:

Class<?> c = getClassByName("TestActivity");
0

4 Answers 4

190

use forName instead..

something like this..

 try {
    Class<?> act = Class.forName("com.bla.TestActivity");
 } catch (ClassNotFoundException e) {
        e.printStackTrace();
}
Sign up to request clarification or add additional context in comments.

4 Comments

You have to give the complete package name as well. eg: com.bla.TestActivity as argument to Class.forName
Can you also do something to receive Class<? extends SomeClass> ?
@Gobliins No - the compiler can't guarantee what kind of class you are going to get, so it gives you a Class<?>. If you know what kind of class you are going to get, you will have to cast it (even still, you get unchecked cast warnings because the cast is not safe).
@Gobliins Check out my answer on how to get a subclass of a certain type.
15

You can use Class::forName to get a class object of unknown type. If you want to get a typed class, you can use Class::asSubclass on the class returned by Class::forName:

Class<? extends Activity> activityClass = Class.forName("com.example.TestActivity")
                                               .asSubclass(Activity.class);

Of course you will also have to handle a bunch of different types of exceptions. As is usual when dealing with reflection.

Comments

4

The Class.forName seems to have exceptions on it. This is just to expand upon the above to address this issue.

try { t = Class.forName("com.package.classname"); } catch (Exception ignored){}

3 Comments

The usual way on SO to answer like this would be to edit their answer. Although since exceptions are plentiful in Java (and your code just ignores it), a comment would be enough to address it.
@crazyhatfish - It seems as though Patrick may not have had the privileges to do anything helpful except post his own answer.
@amess Whoops, your right, I forget comments need rep. Thanks for correcting me.
2

I also had a similar requirement, I had a json coming from backend which contains the screen and activity mapping. Since the json in common for both iOS/ Android, we couldnt add terms like Activity into the json, so this is what we did

  1. In json for all Activity or Viewcontrollers, use simple names ie for HomeActivity and HomeViewController we will use "Home" in the json

  2. In app, we parse the json and I have written the below utility methods to get the activity dynamically

To get the name of the class (ie if we pass Home, we will get back com.package.HomeActivity)

    fun getClassInfoFor(name: String, context: Context):String{
        var str = "${context.getPackageName()}.${name}Activity"
        return str
    }

Now to get class from string

        try {
            val className = Utilties.getClassInfoFor(activityNameFromJSON, context)
            val fetchedClass = Class.forName(className)
            val showDetailsIntent = Intent(context, fetchedClass)
            context.startActivity(showDetailsIntent)
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        }

This way I can easily manage multiple classes with the same method. I use this in a recycler view where my every cell navigates to a different activity.

4 Comments

Please note that your answer is in Kotlin ;) Probably alter it a little bit to make it Java ?
@LMD probably most of android developers searching for an answer need kotlin version, not java ;)
@RuslanBerozov The op has tagged the question as [java] so I would expect at least a Java version (additional Kotlin is fine too, of course).
@LMD sorry, but op posted a question at 2012. It's really difficult to imagine that he knowed about Kotlin at that time. The point is that question is also marked as [android], and nowadays I expect Kotlin version preferably.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.