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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With