我正在尝试从字符串创建Activity
类并将其传递给静态方法。我在SO上发现这个将字符串传递给一个类。 FirstActivity
已经创建。
SecondActivity
String myClass = "com.package.FirstActivity";
Class<?> myClass = Class.forName(myClass);
//this works
//Intent myIntent = new Intent(getApplicationContext(), myClass);
//I want to pass to a static method, but it gives a error. Class cannot cast to Activity
StaticMethod.processThis(myClass , "test");
STATICMETHOD
public static void processThis(Activity contextActivity, String str) {
//do processing
}
如何让processThis
工作?如果我理解正确,Activity
也是一个类?
答案 0 :(得分:10)
您需要创建FirstActivity的新实例。如果此类具有无参数的构造函数,则可以执行以下操作:
String myClass = "com.package.FirstActivity";
Class<?> myClass = Class.forName(myClass);
Activity obj = (Activity) myClass.newInstance();
Intent myIntent = new Intent(getApplicationContext(), myClass); //Maybe here also obj must be needed
//Noe pass your object here
StaticMethod.processThis(obj, "test");