7

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

Community
  • 1
  • 1
Lizard
  • 43,732
  • 39
  • 106
  • 167

4 Answers4

5

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

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
3

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);
Robin
  • 24,062
  • 5
  • 49
  • 58
1

Use reflection.

Here's an example

patros
  • 7,719
  • 3
  • 28
  • 37
-1

With the reflection API. Something like this:

    Method method = getClass().getDeclaredMethod(functionName);
    method.invoke(this);
unbeli
  • 29,501
  • 5
  • 55
  • 57