目标方法
public class Test2 {
public String name;
public int age;
public void doSomething(){
System.out.println("无参方法");
}
private void haveSomething(String gg,int mm){
System.out.println(gg+"+++++++++"+mm);
}
}
测试类
public class Test {
public static void main(String[] args) {
try {
Class c1= Class.forName("com.itheima.reggie.util.Test2");
Object object= c1.newInstance();
Method haveSomething= c1.getDeclaredMethod("haveSomething", String.class, int.class);
//必须设置为true,否则将不能获取到该方法 IllegalAccessException
haveSomething.setAccessible(true);
haveSomething.invoke(object,"太君",78);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
结果:
太君+++++++++78
Process finished with exit code 0