org.springframework.util.MethodInvoker
这个类是干什么用的?
通过类名就可以看出这个类就是调用方法用的,给出刚刚测试的代码:
public class Main {
public static void main(String[] args) throws IOException, URISyntaxException, InvocationTargetException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException {
Test test = new Test();
MethodInvoker methodInvoker = new MethodInvoker();
methodInvoker.setTargetObject(test);
methodInvoker.setTargetMethod("print");
methodInvoker.prepare();
methodInvoker.invoke(); // 相当于调用test.print();
methodInvoker.setTargetObject(test);
methodInvoker.setTargetMethod("add");
Object[] params = {10, 20};
methodInvoker.setArguments(params);
methodInvoker.prepare();
System.out.println(methodInvoker.invoke()); // 输出“30”,相当于调用test.add(10, 20);
methodInvoker.setTargetClass(Test.class);
methodInvoker.setTargetMethod("staticPrint");
methodInvoker.setArguments(null);
methodInvoker.prepare();
methodInvoker.invoke(); // 相当于调用Test.staticPrint();
}
}
class Test {
public void print() {
System.out.println("调用print");
}
public int add(int a, int b) {
return a + b;
}
public static void staticPrint() {
System.out.println("调用staticPrint");
}
}