一、概述
定义:
运行状态中,对任意类,可获取其所有方法和属性;对任意对象可调用其任意方法和属性。这种动态操作称之为 Java 反射机制
Java 反射机制的功能
- 运行时判断任意对象所属类
- 运行时构造任意类的对象
- 运行时判断任意类的方法和属性
- 运行时调用任意实例的方法
- 生成动态代理
Java 反射机制应用场景
- 逆向代码 (反编译)
- 与注解结合的框架 (retrofit)
- 单纯的反射机制应用框架 (EventBus)
- 动态生成类框架 (Gson)
反射的具体方法
获取对象的方法
- Class 类的 forName(String clazzName) 静态方法 参数问完整类名
- 通过类的 class 属性
调用对象的 getClass() 方法
// 第一种 class1 = Class.forName("com.mune.example.Person"); // 第二种 class2 = Person.class; // 第三种 Person person = new Person(); Class<?> class3 = person.getClass();
获取成员变量的方法
getDeclaredFields()
方法 获取class 对象的所有属性getField()
方法 获取class 对象的public 属性getDeclaredField(String propertyName)
方法 通过属性名获取class指定属性getField(String propertyName)
方法 通过属性名获取class指定public属性
获取对象方法的方法
getDeclaredMethods()
获取 class 对象所有声明的方法getMethods()
获取 class 对象的所以有的public 方法 (包括父类的方法)getMethod(String name, Class<?>... parameterTypes)
获取Class 对象对应类的、带指定参数列表的的public 方法getDeclaredMethod(String name, Class<?>... parameterTypes)
获取Class 对象对应类的、带指定参数列表的的方法
获取构造函数的方法
getDeclaredonstrutors()
获取class 对象声明的所有构造函数getConstructors()
获取class 对象声明的public构造函数getDeclaredonstrutor(Class<?>... parameterTypes)
获取指定声明的构造 函数getConstructor(Class<?>... parameterTypes)
获取指定声明的pubilic构造函数
其他方法
Annotation[] annotations = (Annotation[]) class1.getAnnotations();//获取class对象的所有注解
Annotation annotation = (Annotation) class1.getAnnotation(Deprecated.class);//获取class对象指定注解
Type genericSuperclass = class1.getGenericSuperclass();//获取class对象的直接超类的 Type
Type[] interfaceTypes = class1.getGenericInterfaces();//获取class对象的所有接口的type集合