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?
repeated = new String(new char[n]). replace("\0", s);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With