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?

2
  • 5
    Typically, this is a bad idea. What are you aiming to accomplish with this? Commented Dec 22, 2012 at 21:19
  • 1
    I think it would be the same approach as this; stackoverflow.com/questions/160970/… Commented Dec 22, 2012 at 21:20

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can achieve this using Java Reflection

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.