Getting class by its name

JavaAndroidClass

Java Problem Overview


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");

Java Solutions


Solution 1 - Java

use forName instead..

something like this..

 try {
    Class<?> act = Class.forName("com.bla.TestActivity");
 } catch (ClassNotFoundException e) {
        e.printStackTrace();
}

Solution 2 - Java

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.

Solution 3 - Java

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){}

Solution 4 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUrhoView Question on Stackoverflow
Solution 1 - JavangeshView Answer on Stackoverflow
Solution 2 - JavaraphinesseView Answer on Stackoverflow
Solution 3 - JavaPatrickView Answer on Stackoverflow
Solution 4 - Javaanoop4realView Answer on Stackoverflow