Getting class by its name

后端 未结 5 1267
既然无缘
既然无缘 2020-11-28 07:58

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 = getCl         


        
5条回答
  •  春和景丽
    2020-11-28 08:24

    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.

提交回复
热议问题