在类中调用已知函数(带参数),其名称由字符串变量定义

时间:2015-06-14 22:48:13

标签: java function class variables

我有一堆各种名称的类,每个类都有一个performLogic函数,它接受许多预设参数(总是相同的):

public final class DoSomeAction extends SetupAction {
    public void performLogic(param1, param2...

我想要一种可以这样称呼它的方式:

String actionName = "DoSomeAction";
actionName.performLogic(param1, param2...);

希望这清楚我想要做的事情。

感谢您的反馈,并指向我的class.forName() 经过一些进一步的研究后,我能够实现以下目标:

try {
    Class actionClass = Class.forName(blockAction);

    Object obj = actionClass.newInstance();

    Class[] parameterTypes = new Class[2];
    parameterTypes[0] = String.class;
    parameterTypes[1] =  String.class;

    Method performLogic = actionClass.getDeclaredMethod("performLogic", parameterTypes);

    performLogic.invoke(obj, param1, param2);
}
catch(ClassNotFoundException e) {
    cat.error("Class not found: " + e.toString());
}

1 个答案:

答案 0 :(得分:2)

您可以使用反射

Object action = ???; // perhaps you need .newInstance() for action class
                     // Hopefully you have a interface with performLogic

String methodName = "performLogic";
try {
    Method method = action.getClass().getMethod(methodName, param1.class, param2.class);
    method.invoke(action, param1, param2);
} catch (SecurityException | NoSuchMethodException e) {
    // Error by get Method
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {        
    // Error by call Method
}