PRELOADER

当前文章 : 《Java反射机制》

5/5/2019 —— 

前言

  Java 反射机制是指在运行状态中,对于任意一个类,都能够获得这个类的所有属性和方法,对于任意一个对象都能够调用它的任意一个属性和方法。这种在运行时动态的获取信息以及动态调用对象的方法的功能称为Java 的反射机制。

反射机制的作用

  反射机制的目的就是要增加程序的灵活性,它能够有效的避免将程序写死在我们的代码中。
举个例子,不使用反射:实我们例化一个 A()对象,new一个A(),这时候,我们如果想要去实例化别的类, 那么必须去修改源代码,并重新编译。
使用反射: class.forName(“A”).newInstance(); 而且这个类描述我们可以写到配置文件中,如 ***.xml配置文件, 这样如果想实例化其他类,只要修改配置文件的”类描述”就可以了实现,不需要再次去修改我们的代码并编译。

获取Class对象的3种方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Life life = new Life();
Class class1 = life.getClass();
System.out.println(class1);
// 2 任意数据类型都具备一个class静态属性
Class class2 = Life.class;
System.out.println(class2);
Class class3= Class.forName("com.reflect.Life");
System.out.println(class3);
//三种方式的比较:前两种方式,我们必须明确Left类型,而第三种方式知道这种类型的字符串就行.这种扩展更强。

```

### 获取构造方法

```Java
Class class3= Class.forName("com.reflect.Life");
//获取无参构造
Life life1 = (Life)class3.newInstance();
//获取有参构造
Constructor constructor = class3.getConstructor(String.class);
Life life2 = (Life)constructor.newInstance("炸鸡");

```

### 获取成员变量

```Java
Class class3= Class.forName("com.reflect.Life");
// getDeclaredFields() 获取当前类所有属性
// getFields() 获取公有属性(包括父类)
Field fields[] = class3.getDeclaredFields();
// 取消安全检查才能获取或者修改private修饰的属性,也可以单独对某个属性进行设置
Field.setAccessible(fields, true);
for (Field field : fields) {
System.out.println("*******属性名:" + field.getName() + "***属性值:" + field.get(class3.newInstance()) + "****属性类型:" + field.getType());
}
Field meal = class3.getDeclaredField("meal");
// 取消安全检查才能获取或者修改private修饰的属性,也可以批量对所有属性进行设置
meal.setAccessible(true);
meal.set(class3.newInstance(), "啤酒");

获取成员方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Class  class3=  Class.forName("com.reflect.Life");
// getMethods()获取公有方法
// getDeclaredMethods()获取所有方法
Method[] methods = class3.getDeclaredMethods();
// 取消安全性检查
Method.setAccessible(methods, true);
for (Method method : methods) {
System.out.println("*******方法名:" + method.getName() + "*******返回类型:" + method.getReturnType().getName());
}
// 获取无参方法
Method getMethod = class3.getDeclaredMethod("getMeal");
getMethod.setAccessible(true);
// 调用无参方法
getMethod.invoke(class3.newInstance());
// 获取有参方法
Method setMethod = class3.getDeclaredMethod("setMeal", String.class);
setMethod.setAccessible(true);
// 调用有参方法
setMethod.invoke(class3.newInstance(), "包子");