Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Possible Duplicate:
Calling a method named “string” at runtime in Java and C

I need to be able to call a function, but the function name is stored in a variable, is this possible. e.g:

public void foo ()
{
     //code here
}

public void bar ()
{
     //code here
}

String functionName = "foo";

// i need to call the function based on what is functionName

Anyhelp would be great, thanks

share|improve this question
If you explain why you think you need to do this, we can perhaps offer alternatives. – polygenelubricants Jun 14 '10 at 15:36

marked as duplicate by polygenelubricants, Péter Török, jjnguy, Matthew Flaschen, Graviton Jun 15 '10 at 2:06

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5 Answers

up vote 4 down vote accepted

Yes, you can, using reflection. However, consider also Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection. If at all possible, use interfaces instead. Reflection is rarely truly needed in general application code.

See also

Related questions

share|improve this answer

Use reflection.

Here's an example

share|improve this answer

Easily done with reflection. Some examples here and here.

The main bits of code being

String aMethod = "myMethod";

Object iClass = thisClass.newInstance();
// get the method
Method thisMethod = thisClass.getDeclaredMethod(aMethod, params);
// call the method
thisMethod.invoke(iClass, paramsObj);
share|improve this answer

What you are looking for is reflection, here is a similar question: http://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string

share|improve this answer

With the reflection API. Something like this:

    Method method = getClass().getDeclaredMethod(functionName);
    method.invoke(this);
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.