开发者

How to call Java function from string stored in a Variable [duplicate]

开发者 https://www.devze.com 2023-01-03 05:03 出处:网络
This question already has answers here: 开发者_JAVA技巧 Closed 12 years ago. Possible Duplicate: Calling a method named “string” at runtime in Java and C
This question already has answers here: 开发者_JAVA技巧 Closed 12 years ago.

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


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

  • Java Tutorials/Reflection API
  • Java Advanced Language Topics/Reflection

Related questions

  • Calling a method named “string” at runtime in Java and C


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);


Use reflection.

Here's an example


With the reflection API. Something like this:

    Method method = getClass().getDeclaredMethod(functionName);
    method.invoke(this);
0

精彩评论

暂无评论...
验证码 换一张
取 消