调用运行时类的指定方法
/*
如何操作运行时类中的指定的方法
(一般不用此方法,使用getMethod():只获取运行时类中声明的public权限方法)
*/
@Test
public void testMethod() throws Exception {
Class clazz = Person.class;
//创建运行时类对象
Constructor declaredConstructor = clazz.getDeclaredConstructor();
Object o = declaredConstructor.newInstance();
Person p = (Person) o;
//1.使用getMethod():获取运行时类中声明的指定方法(public权限方法)
Method display = clazz.getMethod("display", String.class, int.class);
display.invoke(p,"uuh",12);
//2.使用getMethod():获取private权限方法失败,返回:java.lang.NoSuchMethodException: com.atguigu.java.Person.show(java.lang.String)
// Method show = clazz.getMethod("show", String.class);
// show.invoke(p,"show");
}
/*
如何操作运行时类中的指定方法
(需要掌握,使用getDeclaredMethod()获取运行时类中声明的所有方法)
*/
@Test
public void testMethod1() throws Exception{
Class clazz = Person.class;
//创建运行时类对象
Constructor declaredConstructor = clazz.getDeclaredConstructor();
Object o = declaredConstructor.newInstance();
Person p = (Person) o;
//2.使用getDeclaredMethod():获取运行时类中声明的指定方法(任意权限)
//public方法
Method display = clazz.getDeclaredMethod("display", String.class, int.class);
display.invoke(p,"display",12);
//private方法,抛出java.lang.IllegalAccessException,说明获取到了该方法却无法使用
// Method show = clazz.getDeclaredMethod("show", String.class);
// show.invoke(p,"中国");
Method show = clazz.getDeclaredMethod("show", String.class);
//获取使用权限
show.setAccessible(true);
//3.调用方法的invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参
//invoke()的返回值即为对应类中调用方法的返回值
show.invoke(p,"中国");
System.out.println("***********如何调用静态方法***********");
//private static void showDesc()
Method showDesc = clazz.getDeclaredMethod("showDesc");
showDesc.setAccessible(true);
showDesc.invoke(Person.class);
//showDesc.invoke(p)也行
}