将String转换为Activity类

时间:2011-10-29 20:08:49

标签: java android string class android-activity

我正在尝试从字符串创建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也是一个类?

1 个答案:

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