7

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?

Community
  • 1
  • 1
Or K
  • 195
  • 1
  • 3
  • 11
  • 5
    Typically, this is a bad idea. What are you aiming to accomplish with this? – Makoto Dec 22 '12 at 21:19
  • 1
    I think it would be the same approach as this; http://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string – Steve101 Dec 22 '12 at 21:20

3 Answers3

5

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.

Reimeus
  • 152,723
  • 12
  • 195
  • 261
1

You can achieve this using Java Reflection

Rohit Jain
  • 195,192
  • 43
  • 369
  • 489
RobAu
  • 17,042
  • 8
  • 69
  • 108
1

you can do this using reflection. but the method you provided is not java. the return type is missing. why do you want to do this? here is a link, in case you go this route: invoking a static method using reflections

Community
  • 1
  • 1
mindandmedia
  • 6,292
  • 1
  • 21
  • 33