Java 反射

结论: 反射出来的只是字节码

反射: 就是把 Java 类中的各种成分映射成相应的 Java 类

一个类中的组成部分: 成员变量 | 方法 | 构造方法 | 包等信息用 Field | Method | Contructor | Package 等实例对象表示

 1 package 反射;
 2 
 3 import java.beans.PropertyDescriptor;
 4 import java.lang.reflect.Field;
 5 import java.lang.reflect.Method;
 6 
 7 public class Reflect {
 8     public static void main(String[] args) throws Exception {
 9         孑小 孑小 = new 孑小("孑小", 28);
10         假装时光能倒流(孑小);
11     }
12 
13     public static <T> void 假装时光能倒流(T t) throws Exception {
14         Field[] field = t.getClass().getDeclaredFields();
15         for (int i = 0; i < field.length; i++) {
16             String fieldName = field[i].getName();
17             // 通过 PropertyDescriptor 调用 set()和 get()
18             PropertyDescriptor descriptor = new PropertyDescriptor(fieldName, t.getClass());
19             Method method = descriptor.getReadMethod();
20             // method 只是字节码, 它不知道调用哪个类的方法
21             Object fieldValueOld = method.invoke(t);
22             System.out.println("[" + fieldName + "=" + fieldValueOld + "]");
23             if (fieldName.equals("age")) {
24                 // 得到所有声明的属性, 包括私有属性
25                 Field age = t.getClass().getDeclaredField("age");
26                 // 私有属性需要暴力反射
27                 age.setAccessible(true);
28                 age.set(t, 23);
29             }
30         }
31         System.out.println(t.toString());
32     }
33 }
 1 package 反射;
 2 
 3 public class 孑小 {
 4     private String name;
 5     private int age;
 6 
 7     public 孑小(String name, int age) {
 8         super();
 9         this.name = name;
10         this.age = age;
11     }
12 
13     public String toString() {
14         return "[name=" + name + ", age=" + age + "]";
15     }
16 
17     public String getName() {
18         return name;
19     }
20 
21     public void setName(String name) {
22         this.name = name;
23     }
24 
25     public int getAge() {
26         return age;
27     }
28 
29     public void setAge(int age) {
30         this.age = age;
31     }
32 }
原文地址:https://www.cnblogs.com/sunjunxi/p/8574808.html