在Java中,每個類都有一個相應的Class對象。當我們編寫一個類,編譯完成後,在生成的.class文件中,就會產生一個Class對象,用於表示這個類的類型信息。
獲取Class實例的三種方式:
(1)利用對象調用getClass()方法獲取該對象的Class實例;
(2)使用Class類的靜態方法forName(),用類的完全名稱獲取一個Class實例;
(3)運用.class的方式來獲取Class實例,對於基本數據類型的封裝類,還可以採用.TYPE來獲取相對應的基本數據類型的Class實例。
例如有Person類:
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
|
package reflectTest; public class Person { private String name; private int age; private static final String a= "Java" ; public Person(String name){ this .name=name; System.out.println( "名字:" +name); } public Person(){ System.out.println( "無參構造函數" ); } public Person(String name, int age){ this .name=name; this .age=age; System.out.println( "名字:" +name+ " 年齡:" +age); } private Person( int age){ this .age=age; System.out.println( "年齡:" +age); } public void print(){ System.out.println( "hello" ); } } |
要想獲得Person的Class實例,可以用以下三種方法:
|
Class class01=Class.forName( "reflectTest.Person" ); |
Class class02=Person. class ; |
|
Class class03= new Person().getClass(); |
反射可以利用類名稱動態生成對象,並且解剖出類的各個組成部分。
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
package reflectTest; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.junit.Test; public class Test01 { @Test public void test01() throws Exception{ //加載字節碼類 Class class01=Class.forName( "reflectTest.Person" ); //獲得有一個參數的構造函數 Constructor con=class01.getConstructor(String. class ); //利用構造函數創建對象 Person person=(Person) con.newInstance( "張三" ); } @Test public void test02() throws Exception{ //加載字節碼類 Class class02=Person. class ; //獲得有兩個參數的構造函數 Constructor con=class02.getConstructor(String. class , int . class ); //利用構造函數創建對象 Person person=(Person) con.newInstance( "李四" , 40 ); } @Test public void test03() throws Exception{ Class class03= new Person().getClass(); //獲得無參的構造函數 Constructor con=class03.getConstructor( null ); //利用構造函數創建對象 Person person=(Person) con.newInstance(); } @Test public void test04() throws Exception{ Class class04=Class.forName( "reflectTest.Person" ); //獲得私有構造函數 Constructor con=class04.getDeclaredConstructor( int . class ); //取消 Java 語言訪問檢查 con.setAccessible( true ); //創建對象 Person person=(Person) con.newInstance( 30 ); } @Test public void test05() throws Exception{ Person p= new Person(); Class class05=Class.forName( "reflectTest.Person" ); //反射出類的方法 Method me=class05.getMethod( "print" , null ); me.invoke(p, null ); } @Test public void test06() throws Exception{ Person p= new Person(); Class class06=Class.forName( "reflectTest.Person" ); //反射類的字段 Field fi=class06.getDeclaredField( "a" ); fi.setAccessible( true ); System.out.println(fi.get(p)); } } |