1.定义:
在类的运行期间,把类中成员抽取为其他类的过程就是反射
2.反射的用途:
为了解决运行时期,对某个实例一无所知的情况下,调用类中属性和方法
3.class反射类:
(1)获取方式:
①通过 类名.class属性
Class<类名> class=类名.class
②通过类路径进行获取
Class<?> aClass = Class.forName("路径")
③通过对象名获取反射类型
类名 class=new 类名() Class class1= class.getclass();
(2)常用方法:
①通过反射类得到实例对象
Class<类名> class=类名.class class.newInstance();
②得到反射类的注解对象
Class<类名> class=类名.class MyAnnotation annotation=class.getAnnotation(MyAnnotation.class)
4.Method方法类:
(1)获取方法:
①得到本类中的所有方法:getDeclaredMethods()
Class<类名> class=类名.class Method[] declaredMethods=class.getDeclaredMethods()
②得到本类中指定的方法:getDeclaredMethod("方法名",参数类型.class)
Method method=class.getDeclaredMethod("方法名",参数类型.class)
③获取本类以及父类的public修饰的方法:getMethods()
Method[] methods=class.getMethods()
④获取本类以及父类中指定public对象:getMethod("方法名",参数类型.class)
Method method=class.getMethod("方法名",参数类型.class)
(2)常用方法:
①invoke(object,参数值)
Class<?> aClass = Class.forName("路径"); Object o=aClass.newInstance(); Method method=aClass.getMethod("方法名",参数类型.class); Object result=method.invoke(o,参数值);
②获取私有方法->强力反射:setAccessible()
Class<?> aClass = Class.forName("路径"); Object o=aClass.newInstance(); Method method1=aClass.getDeclaredMethod("方法名"); method1.setAccessible(true); Object result1=method1.invoke(o);
4.Field属性对象:
(1)获取方法:
①获取本类指定对象:getDeclaredField("属性名")
Class<类名> class=类名.class; Field name=class.getDeclaredField("属性名");
②获取本类中所有的属性对象:getDeclaredFields()
Field[] name=class.getDeclaredFields();
③获取本类和父类中Public修饰的属性:getField("属性名")
Field name=class.getField("属性名");
④获取本类和父类中所有public的属性:getFields()
Field[] name=class.getFields();
(2)常用方法:
①为属性赋值:set(类名,值)
Class<类名> class=类名.class; Field name=class.getDeclaredFiel("属性名"); name.set(类名,值);
②获取属性名:get属性名()
Class<类名> class=类名.class; Field[] declaredFields=class.getDeclaredFields() for(Field f:declaredFields){ f.get属性名() }
③获取属性上的注解对象:getAnnotation()
Class<类名> class=类名.class; Field[] declaredFields=class.getDeclaredFields() for(Field f:declaredFields){ f.get属性名(); MyAnnotation annotation=f.getAnnotation(MyAnnotation.class); anntation.value(); }
5.使用属性文件的案例
(1)属性文件
className="路径"
(2)测试类
//1.加载属性文件 InputStream resourceAsStream = 包名.class.getClassLoader().getResourceAsStream("?.properties"); //2.通过属性类Properties Properties properties=new Properties(); properties.load(resourceAsStream); //3.属性类读取属性文件中指定的key的值 String className = properties.getProperty("className"); //4. 根据类路径得到反射对象 Class<?> aClass = Class.forName(className); //5. 根据反射类创建类对象 Object o = aClass.newInstance(); //6.为属性赋值 Field[] declaredFields = aClass.getDeclaredFields(); for(Field field:declaredFields){ field.setAccessible(true); field.set() } }