7

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?

newbie
  • 958
  • 4
  • 13
  • 25

1 Answers1

10

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");
Ernesto Campohermoso
  • 7,213
  • 1
  • 40
  • 51