1 import java.lang.reflect.Constructor;
2 import java.lang.reflect.*;
3
4 /*Class:代表一個位元組碼檔案的對象,每當有類被加載進記憶體,JVM就會在堆上給
5 * 該類建立一個代表該類的對象。每個類的Class對象是的。
6 *Class類沒有構造方法,獲得類對應的Class方法有3種
7 *1.:getClass()、2.類、接口.class 、3.Class.forName("類全名");
8 *比較推薦使用第3種方式,使用前兩種方式程式擴充性不好。
9 *
10 *Class類中定義了許多關于擷取類中資訊的方法:
11 *1.獲得該類的構造方法,屬性,方法、執行個體的方法。包含特定情況的獲得
12 *2.獲得該類的父類,實作的接口,該類的類加載器,類名、包名等。
13 *3.判斷該類的具體是接口、類、内部類等
14 *4.方法中加Declared表示可以獲得本類定義的任何方法和屬性
15 *
16 *注意:關于獲得到的方法、屬性、構造器的具體操作被封裝在import java.lang.reflect包裡面
17 *Method:裡面最常用的方法invoke(對象,可變參數清單)--調用指定的方法
18 *Field:get/set;擷取和修改屬性值
19 *Constrcutor:使用newInstance(可變參數清單)--調用指定構造方法建立類的執行個體
20 *注意:私有的要調用前先去掉通路權限限制setAccssible()
21 * */
22 public class ReflectionWithClass {
23
24 public static void main(String[] args) throws Exception {
25
26 //第一種方式獲得Class對象,比較麻煩,要先建立對象,再使用對象調用方法
27 HelloKitty ht = new HelloKitty();
28 Class clazz = ht.getClass();
29
30 //第二種方式獲得Class對象。使用靜态的屬性建立
31 Class clazz1 = HelloKitty.class;
32
33 //使用Class對象的靜态方法獲得Class對象
34 Class clazz2 = Class.forName("HelloKitty");
35
36 //獲得該類的類加載器
37 ClassLoader c = clazz2.getClassLoader();
38 System.out.println(c.toString());
39
40 Class clazz3 = String.class;
41 System.out.println(clazz3.getClassLoader());
42
43 //獲得該類的執行個體
44 Object obj = clazz2.newInstance();
45 //獲得該類的構造器---公開的,getDeclaredConstructors()--可以獲得私有的
46 Constructor[] con = clazz2.getDeclaredConstructors();
47 for(Constructor cc:con){
48 System.out.print(cc + " ");
49 }
50
51 //獲得類的方法
52 Method[] mm = clazz2.getDeclaredMethods();
53 for(Method mmm:mm){
54 System.out.print(mmm + " ");
55 }
56
57 System.out.println();
58 //擷取特定的方法
59 Method m = clazz2.getMethod("walk",null);
60 System.out.println(m.toString());
61
62 Field[] f = clazz2.getDeclaredFields();
63 for(Field ff:f){
64 System.out.print(ff+ " ");
65 }
66
67 //調用指定的方法---先擷取,在調用;注意私有方法先設定通路權限
68 Method m1 = clazz2.getMethod("walk", null);
69 System.out.println("hahahhha");
70 m1.invoke(obj,null);
71
72 //調用指定的構造方法建立類執行個體;先擷取在調用
73 Constructor cc = clazz2.getConstructor(int.class,String.class);
74 Object o1 = cc.newInstance(12,"blue");
75
76 //擷取和修改對象的屬性值
77 Field ffs = clazz2.getDeclaredField("age");
78 ffs.setAccessible(true);
79 ffs.set(obj, 29);
80 Object oo = ffs.get(obj);
81 System.out.println(oo);
82
83 }
84
85 }
86
87 class HelloKitty {
88 private int age;
89 public String color = "pink";
90 public HelloKitty() {}
91
92
93 public HelloKitty(int age) {
94 this.age = age;
95 }
96
97 public HelloKitty(int age,String color) {
98 this.age = age;
99 this.color = color;
100 System.out.println("okokok");
101 }
102
103 public void walk(){
104 System.out.println("hhhhhhhhhhhhh");
105 }
106
107 public void talk(int i){
108 System.out.println(i + "----------" + age);
109 }
110 }