我有一堆各种名称的类,每个类都有一个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());
}
答案 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
}