创建一个Caculator 类
package org.example.caculator;
public class Caculator {
private String name;
public Caculator(){
};
public Caculator(String name){
this.name = name;
}
public int add(int a,int b){
return a+b;
}
}
org.example.caculator.Caculator这个是 Caculator的路径,创建一个 o 对象,
通过 cls.getMethod 获取Caculator的add 方法 后面两个是add的两个参数,通过method.invoke();调用这个方法。
package org.example.caculator;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Class<?> cls = Class.forName("org.example.caculator.Caculator");
Object o = cls.newInstance();
Method method = cls.getMethod("add", int.class, int.class);
System.out.println(method.invoke(o,11,44));
}
}