1

I have a variable:

String MyClass = "MyClass" 

and I want to use it here:

Intent intent = new Intent(this, MyClass.class); startActivity(intent); 

or:

Intent intent = new Intent(this, MyClass.ToString().class); startActivity(intent); 

and it doesn't work... How can I pass the value of MyClass to the Intent constructor?

2
  • Before going to start programming ..Just follow the naming conventions.. Commented Mar 28, 2013 at 17:31
  • I don't think its even possible Commented Mar 28, 2013 at 17:33

1 Answer 1

4

First of all, Java naming convention is that variables should be named starting with a lower case letter, and classes with an upper case one. This makes your code confusing, because it looks like you're specifying a class, but you aren't.

In fact, the correct answer is to change your String into a Class object using Class.forName():

Class<?> newActivityClass = Class.forName(myPackage + "." + myClass); startActivity(new Intent (this, newActivityClass)); 

There will be exceptions that you will need to catch and handle appropriately.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.