目录
一、反射
-
反射之操作成员方法
解析:
1.反射操作成员方法的目的:操作Method对象来调用成员方法
2.使用method类进行操作,类型中每个方法都是一个Method类的对象。
1.Method类与Class对象中常用方法
1.1Method getMethod(String name,Class...args);
作用: 根据方法名和参数类型获得对应的方法对象,只能获得public的1.2Method getDeclaredMethod(String name,Class...args);
作用: 根据方法名和参数类型获得对应的方法对象,包括非public的【只能获取本类中的一个】1.3Method[] getMethods();
作用:获得类中的所有成员方法对象,返回数组,只能获得public修饰的且包含父类的1.4Method[] getDeclaredMethods();
作用: 获得类中的所有成员方法对象,返回数组,只获得本类的,包括非public的方法【只能获取本类中所有】1.5Object invoke(Object obj, Object... args)
obj:调用方法所使用的对象,如果是静态方法可以传入null
args:调用方法时传递的参数【实参】
作用:返回值就是该方法对象调用后的返回值,如果是无返回值方法固定返回null
1.6void setAccessible(true) 作用:如果是非public方法,就得调用该方法设置为可访问。
设置"暴力访问"——是否取消权限检查,true取消权限检查,false表示不取消
代码使用演示:
package com.feisi.week7.day1;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
// 创建student类的Class对象
Class<Student> studentClass = Student.class;
Student student = new Student();
// 使用原来类的实例对象传入,调用方法 抽象类中的普通私有方法怎么调用呢 好像通过反射也调用不了,因为无法创建该类的实例化对象
// 使用Class对象创建成员方法对象
// 获取被public修饰的方法
Method method = studentClass.getMethod("show");
System.out.println(method);
method.invoke(student);
// 静态普通方法
Method method1 = studentClass.getMethod("show1");
method1.invoke(null);
// 保护静态方法
Method method2 = studentClass.getDeclaredMethod("show2");
method2.setAccessible(true);
method2.invoke(null);
// 一次性获得多个方法的对象 建议使用下面的方法获取多个,有效避免的报异常的情况
Method[] declaredMethods = studentClass.getDeclaredMethods();