converting a string to a class

2019-02-10 20:47发布

I'm trying to move between one Activity to another based upon some user input.

I'm trying to use:

String myClass = "some_user_input.class"
Intent myIntent = new Intent(getApplicationContext(), myClass);
startActivity(myIntent);

...to move from one activity to another.

I can do this ok where I reference my new activity directly in the hard code and don't try to compile it from text, (i.e. classA.class), however I want to be able to build my Intent by passing it some string compiled by the user.

For example if the user inputs B in an edittext, I want to go to classB.class If the user inputs Z, I want to go to classZ.class.

Is there any way I can compile the class I want to go to using strings which I then convert to a class?

Thanks in advance!

2条回答
欢心
2楼-- · 2019-02-10 21:05

This is my solution using Class.forName() method:

String myClass = "foo.class";
Intent i = new Intent(getApplicationContext(), Class.forName(myClass));
startActivity(i);
查看更多
神经病院院长
3楼-- · 2019-02-10 21:22

The reflection mechanism allows you to do it:

String myClass = "some_user_input";
Class<?> clazz = Class.forName(myClass);
Intent myIntent = new Intent(getApplicationContext(), clazz);

Note that those classes should be included in the android manifest XML.

Also note that I didn't handle the exception in this example :)

查看更多
登录 后发表回答