Getting class by its name
Asked Answered
P

4

101

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");
Pestana answered 12/4, 2012 at 8:23 Comment(0)
L
187

use forName instead..

something like this..

 try {
    Class<?> act = Class.forName("com.bla.TestActivity");
 } catch (ClassNotFoundException e) {
        e.printStackTrace();
}
Lantha answered 12/4, 2012 at 8:26 Comment(4)
You have to give the complete package name as well. eg: com.bla.TestActivity as argument to Class.forNameYemen
Can you also do something to receive Class<? extends SomeClass> ?Coraciiform
@Coraciiform 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).Teddi
@Coraciiform Check out my answer on how to get a subclass of a certain type.Claar
C
13

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.

Claar answered 5/1, 2018 at 13:25 Comment(0)
S
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){}
Schonfield answered 19/4, 2015 at 22:31 Comment(3)
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.Effects
@crazyhatfish - It seems as though Patrick may not have had the privileges to do anything helpful except post his own answer.Consulate
@amess Whoops, your right, I forget comments need rep. Thanks for correcting me.Effects
A
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.

Amelina answered 12/8, 2018 at 11:2 Comment(4)
Please note that your answer is in Kotlin ;) Probably alter it a little bit to make it Java ?Benkley
@LMD probably most of android developers searching for an answer need kotlin version, not java ;)Mouthpiece
@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).Benkley
@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.Mouthpiece

© 2022 - 2024 — McMap. All rights reserved.