我有一堆各种名称的类,每个类都有一个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());
}
最佳答案 你可以使用Reflection
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
}