Java: is there a way to convert text into a class?
I have the input: "ListClients param1 param2"
which splits by " "
to "ListClients", "param1", "param2";
and I want to call a static method from ListClients.
So it would do ListClients.someMethodThatTakesPraams(开发者_运维知识库param1, param2);
is there a way to do that in java?
Yes indeed! You can use Class.getDeclaredMethod
to look up a Method
object given a name and the types of the parameters. For example, to find your someMethodThatTakesParams
method, you could write
Method m = ListClients.class.getDeclaredMethod("someMethodThatTakesParams", ArgType1.class, ArgType2.class);
Here, ArgType1
and ArgType2
are the types of the arguments.
Once you have the method, you can invoke it as follows:
m.invoke(null, arg1, arg2);
Where arg1
and arg2
are the parameters you want to pass. Note that the first argument to invoke
is null
because the method is static.
This approach omits all sorts of weirdness with exceptions you have to catch and security permissions you might have to acquire, but fortunately those aren't that hard to pick up.
Yes you can use reflection. Below is an e.g. of creating a new instance
Class<Object> fc = Class.forName("ListClients");
Object myObj = fc.newInstance();
Here are some examples of invoking methods
The simple hard coded way would be to create an if/else chain and invoke the right method:
String input = "ListClients param1 param2";
String [] args = input.split(" ");
switch( args.length ) {
case 0:
return ListClients.someMethod();
case 1:
return ListClients.someMethod( args[0] );
case 2:
return LIstClients.someMethod( args[1] );
default:
return // something default
}
While this may seem a bit antiquate, it is very safe, because you program exactly how your code should be invoked.
The other solution would involve using reflection as others mention:
String input = "ListClients param1 param2";
String [] args = input.split(" ");
Class[] types = new Classs[ args.length ];
Object[] values = new Object[ args.lenght ];
for( int i = 0 ; i < types.lenght ; i++ ) {
types[i] = String.class;
values [i] = args[i];
}
ListClients.class
.getDeclaredMethod("someMethod", types )
.invoke( null, values );
All that surrounded by a number of reflection checked exceptions.
You should consider how dynamic you need your application to be, and / if you would do something to prevent a wild call like this: "System.exit(0)" be invoked or any other sort of code injection.
Reflection will be your friend.
精彩评论