Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to code in Java [duplicate]

Tags:

java

Possible Duplicate:
How do I invoke a java method when given the method name as a string?
How do I programmatically compile and instantiate a Java class?

I have a function:

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

I want to read a string from either the user or a file, and if the string "fun1()" appears, I'd call fun1.

I don't want to do this with a switch statement, because I have a lot of functions.

There is any way to call a function using strings?

like image 911
Or K Avatar asked Dec 22 '12 21:12

Or K


People also ask

How do you duplicate a string in Java?

repeated = new String(new char[n]). replace("\0", s);


1 Answers

You could 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. Reflection bring with it a number of disadvantages such as being difficult to debug and rendering automatic refactoring tools such as those in Eclipse effectively useless.

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

like image 121
Reimeus Avatar answered Sep 19 '22 21:09

Reimeus