Convert String to Java Code

Possible duplicate:
How to call a java method when specifying a method name as a string?
How to programmatically compile and instantiate a Java class?

I have a function:

fun1() { System.out.print("hello"); } 

I want to read a line from a user or file, and if the line "fun1()" appears, I would call fun1.

I do not want to do this with the switch statement, because I have many functions.

Is there a way to call a function using strings?

+7
source share
3 answers

You can use reflection here:

 Method method = MyClass.class.getDeclaredMethod("fun1", new Class[] {}); method.invoke(this, null); 

Consider first, however, if you can avoid using reflection, then do it. Reflection brings with it a number of shortcomings, such as the complexity of debugging and rendering of automatic refactoring tools, such as those in Eclipse, are practically useless.

Rethink your design; you can probably better solve the problem with cleaner class decomposition, better polymorphism, etc.

+5
source

You can achieve this using Java Reflection

+1
source

You can do this using reflection. but the method you provided is not java. no return type. why do you want to do this? here's a link if you go this route: calling a static method using reflections

+1
source

All Articles