invoke调用成员方法(无参和有参):

1.无参:
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//1.创建对象
Cat cat = new Cat();
//2.获取class对象
Class clazz = cat.getClass();
//3.获取任意构造方法
Constructor c1 = clazz.getDeclaredConstructor(String.class, int.class);
//4.创建calss在类中的对象
Method m = clazz.getMethod(“eat”);
//5.调用invoke方法
m.invoke(cat);
}
2.有参:
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//1.创建对象
Cat cat = new Cat();
//2.获取class对象
Class clazz = cat.getClass();
//3.获取任意构造方法
Constructor c1 = clazz.getDeclaredConstructor(String.class, int.class);
//4.创建calss在类中的对象
Method m = clazz.getMethod(“eat”,String.class,int.class);
//5.调用invoke方法
m.invoke(cat,“六七”,12);
}
3. 使用暴力访问权限获取私有成员方法有参:
4. public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//1.创建对象
Cat cat = new Cat();
//2.获取class对象
Class clazz = cat.getClass();
//3.获取任意构造方法
Constructor c1 = clazz.getDeclaredConstructor(String.class, int.class);
//4.创建calss在类中的对象
//Cat c =(Cat) c1.newInstance(“小飞鱼”,12);
Method m = clazz.getDeclaredMethod(“eat”,String.class,int.class);
//5.使用暴力访问权限获取私有成员方法
m.setAccessible(true);
//6.调用invoke方法
m.invoke(cat,“六七”,12);
}

你可能感兴趣的:(笔记)