反射
特点:
- 运行程序在运行时进行自我检查并对内部成员进行操作。
- 反射主要是指程序可以访问,检测和修改它本身状态或行为的一种能力,并且根据自身行为的状态和结果,调整或修改应用所描述行为的状态和相关的语义。
作用:
- 在运行时判断任意一个对象所属的类。
- 在运行时获取类的对象。
- 在运行时访问java对象的属性,方法和构造方法等。
java.lang.reflect类库里面主要的类
- Field:表示类的成员变量。
- Method:表示类中的方法。
- Constructor:表示类的构造方法。
- Array:该类提供了动态创建数组和访问数组元素的静态方法。
获取Class对象的常用方式
Object->getClass();任何数据类型(包括基本数据类型)都有一个“静态”的class属性;- 通过Class类的静态方法 Class.forName(string className);
通过Class对象获取某个类中的构造方法
#获取构造方法 - 批量获取 Constractor[] getConstractors();//公有 Constractor[] getDeclaredConstractors(); //所有声明的 - 单独获取 Constractor getConstractor();//公有 Constractor getDeclaredConstractor();//所有声明的 - 调用 Class cls=Class.forName("com.reflectTarget"); Constractor con= cls.getDeclaredConstractor(int.class);//传入参数 con.setAccessable(true); //忽略访问修饰符,设置可以调用私用的方法 ReflectTarget reflectTarget= con.newInstance(1); #获取字段 - 批量获取 Field[] getFields();//公有 Field[] getDeclaredFields(); //所有声明的 - 单独获取 Field getField();//公有 Field getDeclaredField();//所有声明的 - 设置字段值 Field --> public void set(Object obj,Object value) obj:设置字段所在的对象 value:为字段设置值 Class cls=Class.forName("com.reflectTarget"); Field f=cls.getField("fieldName"); ReflectTarget reflectTarget=cls.getConstractor().newInstance(); f.setAccessable(true); f.set(reflectTarget,"测试"); #获取成员变量 - 批量获取 Method[] getMethods(); Method[] getDeclaredMethods(); - 单独获取 Method getMethod(String name,Class<?>...parameterTypes); Method getDeclaredMethod(String name,Class<?>...parameterTypes); - name:方法名 - parameterTypes:返回的参数类型 - 调用方法 Method --> public void invoke(Object obj,Object...args); - obj:要调用方法的对象。 - args:调用方法时所传递的实参。 Class cls=Class.forName("com.example.spring.factory.reflect.ReflectTarget"); ReflectTarget reflectTarget=(ReflectTarget)cls.getDeclaredConstructor().newInstance(); Method m=cls.getMethod("isPublic",String.class); m.setAccessable(true); m.invoke(reflectTarget,"我的参数"); #获取注解信息 Annotation annotations=cls.getAnnotations(); //判断是否拥有指定注解类型的field booblean hasAnnoation=field.isAnnotationPresent(PersionInfoAnnotation.class); if(hasAnnoation){ //获取注解 PersionInfoAnnotation pi=field.getAnnotation(PersionInfoAnnotation.class); //获取注解对应值 }
反射获取方式:例如spring框架
- xml文件
- 注解