Java: is there a way to convert text to class?

I have an input: "ListClients param1 param2" which is broken " "into"ListClients", "param1", "param2";

and I want to call a static method from ListClients.

So that would do ListClients.someMethodThatTakesPraams(param1, param2);

Is there any way to do this in java?

+3
source share
4 answers

Yes indeed! You can use Class.getDeclaredMethodto search for an object Methodwith the name and types of parameters. For example, to find your method someMethodThatTakesParams, you can write

Method m = ListClients.class.getDeclaredMethod("someMethodThatTakesParams", ArgType1.class, ArgType2.class);

Here ArgType1and ArgType2are the types of arguments.

Once you have a method, you can call it like this:

m.invoke(null, arg1, arg2);

arg1 arg2 - , . , invoke null, .

, , , , , , , , .

+5

, . , ,

Class<Object> fc = Class.forName("ListClients");
   Object myObj = fc.newInstance();

+3

if/else :

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         
}

, , , .

, :

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 );

, , .

You should think about how dynamically your application is needed, and / if you do something to prevent a wild call like this: “System.exit (0) is called” or any other type of code injection .

+2
source

Reflection will be your friend.

-1
source

Source: https://habr.com/ru/post/1786262/


All Articles