基本概念
反射机制
在运行状态中,对任意一个类,都能知道这个类的所有属性和方法;对任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取信息以及动态调用对象方法的功能称之为反射机制
作用
1) 运行时判断一个任意对象的所属的类
2) 运行时构造任意一个对象的类
3) 运行时判断任意一个类的所有成员方法和成员变量
4) 运行时调用任意一个类的对象的方法
5) 生成动态代理
示例代码
1.获取类的方式
/**针对PersonInterface 和 Person**/
1) Class<?> class = Class.forName(“com.gjg.Person”);
2) Class<?> class = Person.class
3) Person person = new Person();
Class<?> class = person.getClass();
//用class创建实例
Person person = (Person)class.newInstance();
2.获取父类及接口的方式
1) 获取所有实现的接口
Class<?>[] interfaces = class.getInterfaces();
2) 获取父类
Class<?> superclass = class.getSuperclass();
3.获取构造器的方式
1) 获取带参数的public构造器
Constructor constructor = class.getConstructor(String.class);
2) 获取所有public构造器
Constructor[] constructors = class.getConstructors();
3) 获取不用区分public的构造器 待一个String参数
Constructor constructor = class.getDeclaredConstructor(String.class);
4) 获取所有构造器
Constructor[] constructors = class.getDeclaredConstructors();
//用构造器创建实例
Person person = (Person)constructor.newInstance(“Gjg”);
4.获取方法的方式
1) 获取public setName(String name) 方法
Method methodSetName = class.getMethod(“setName”,String.class);
2) 获取 private setAge(int age) 方法
Method methodSetAge = class.getDeclaredMethod(“setAge”,int.class);//* int.class 与 Integer.class 是不同的
3) 获取所有的public方法 (包含父类的public方法)
Method[] publicMethods = class.getMethods();
4) 获取所有的方法
Method[] methods = class.getDeclaredMethods();
//由于是private方法 在调用前要进行改变其访问区域
methodSetAge.setAccessible(true)
methodSetAge.invoke(person,28);//person是对象 28 是实参值
5.获取成员属性的方式
1) 根据变量名获取public的变量
Field field = class.getField(“country”);
2) 根据变量名获取任意限定符的变量
Field field = class.getDeclaredField(“country”);
3) 获取所有public的变量
Field[] fields = class.getFields();
4) 获取所有变量,不受限定符限制
Filed[] fields = class.getDeclaredFields();
//动态改变属性值,如果是private需要先改变其限定性
field.setAccessible(true);
filed.set(person,”Gjg”);//person所属对象 “Gjg”实参
//获取属性值
String name = filed.get(person);
6.获取注解的方式 (XmlE是个注解示例)
1) 获取指定类型的注解(field method class上的包含继承)
Annotation annotation = filed.getAnnotation(XmlE.class);
2) 获取所有注解(field method class上的包含继承)
Annotation[] annotations = field.getAnnotations();
3) 获取指定类型的注解(field method class上的不包含继承)
Annotation annotation = field.getDeclaredAnnotation(“XmlE.class”);
4) 获取所有注解(filed method class 不包含继承)
Annotation[] annotations = filed.getDeclaredAnnotations();
//转换得到注解对象
XmlE xmlE = (XmlE)annotation;
//得到注解的类型
Class annotationType = annotation.annotationType();
//得到反射中某个值
String name = xmlE.name();
注意事项
1.getDeclaredXXX()与getXXX()
引用块内容
getDeclaredXXX():自身,不受限定符限制
getXXX():所有public 包含父类中的