什么是反射:
反射就是把java类中的各种成分映射成一个个的Java对象
例如:一个类有:成员变量、方法、构造方法、包等等信息,利用反射技术可以对一个类进行解剖,把个个组成部分映射成一个个对象。
反射做什么:
在运行时判断任意一个对象所属的类;
在运行时构造任意一个类的对象;
在运行时判断任意一个类所具有的成员变量和方法;
在运行时调用任意一个对象的方法;生成动态代理。
JAVA有着一个非常突出的动态相关机制:Reflection。
这个字的意思是“反射、映象、倒影”,用在Java身上指的是我们可以于运行时加载、探知、使用编译期间完全未知的classes。换句话说,Java程序可以加载一个运行时才得知名称的class,获悉其完整构造(但不包括methods定义),并生成其对象实体、或对其fields设值、或唤起其methods。这种“看透class”的能力(the ability of the program to examine itself)被称为introspection(内省、内观、反省)。Reflection和introspection是常被并提的两个术语。
反射具体实现:
//获取Class对象
//通过类名. class获取
Class c1 = Person. class;
//通过Class. forName获取
Class c2 = Class . forName(" com.f.entity. Person");
//通过对象. getClass()获取
Person p = new Person();
Class c3 = p. getClassO;
//基本数据类型int
Class<Integer> C4 = Integer . TYPE;
//获取这个类中所有的属性
FieldO fields = c1. getDeclaredFieldsO);
for(Field f:fields) {
System. out . println(f . getName());
}
//创建类的对象
0bject o = c1. newInstance();0bject o2 = c1. newInstance();
//获取指定的字段,属性是set、get方法把set和get干掉,后面的部分第一个字母小写 。
Field f = c1. getDeclaredField("name");
Class fType = f.getType();
//为字段赋值
System. out . println(o);
System. out . println(o2);
//把字段变为可访问
f . setAccessible(true);
//为某个对个的字段赋值
f.set(o, "abc");
f.set(o2, "def");
System. out. println(o);
System. out . println(o2);