Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String to an Activity class

I am trying to create an Activity class from a string and pass it to a static method. I found this on SO to pass a string into a class. FirstActivity is already created.

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
}

How can I get processThis to work? If I understand correctly, an Activity is also a class?

like image 678
newbie Avatar asked Oct 29 '11 20:10

newbie


1 Answers

You need to create a new instance of FirstActivity. If this class has a constructor with no-aruments you can do the following:

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");
like image 141
Ernesto Campohermoso Avatar answered Oct 13 '22 00:10

Ernesto Campohermoso