最近和一位師兄交流了一下Java,真可謂是大有收獲,讓我好好的學習了一下javad的反射機制,同終於明白了spring等框架的一個基本實現的思想,那么今天就和大家分享一下java的反射機制。
反射,reflection,聽其名就像照鏡子一樣,可以看見自己也可以看見別人的每一部分。在java語言中這是一個很重要的特性。下面是來自sun公司官網關於反射的介紹:
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
The ability to examine and manipulate a Java class from within itself may not sound like very much, but in other programming languages this feature simply doesn't exist. For example, there is no way in a Pascal, C, or C++ program to obtain information about the functions defined within that program.
One tangible use of reflection is in JavaBeans, where software components can be manipulated visually via a builder tool. The tool uses reflection to obtain the properties of Java components (classes) as they are dynamically loaded.
那么解釋一下就是,反射是java語言的一個特性,它允程序在運行時(注意不是編譯的時候)來進行自我檢查並且對內部的成員進行操作。例如它允許一個java的類獲取他所有的成員變量和方法並且顯示出來。這個能特定我們不常看到,但是在其他的比如C或者C++語言中很不就存在這個特性。一個常見的例子是在JavaBean中,一些組件可以通過一個構造器來操作。這個構造器就是用的反射在動態加載的時候來獲取的java中類的屬性的。
反射的前傳:類類型 Class Class
java中有一個類很特殊,就是Class類,很多朋友在寫程序的時候有用過比如Apple.class來查看類型信息,大家就可以把它理解為封裝了類的信息,很多解釋說Class類沒有構造器,其實是有的,只不過它的構造方法是private的(構造函數還有private的??有,這樣是為了禁止開發者去自己創建Class類的實例)。我們可以看一下JDK中源碼:
注釋很明確的告訴了我們,這個類是有JVM來創建的,所以我們就不用麻煩了。如果我們拿到一個類的類型信息,就可以利用反射獲取其各種成員以及方法了。(注:Class 從JDK1.5版本后就開始更多為泛型服務了)那么我們怎么拿到一個類型的信息呢?假設我們有一個Role類:
1 package yui;
2
3 /**
4 * A base class having some attributes and methods
5 * @author Octobershiner
6 * @since 2012 3 17
7 *
8 * */
10 public class Role {
11
12 private String name;
13 private String type;
14
15 // Constructors
16 public Role(){
17 System.out.println("Constructor Role() is invoking");
18 }
19 //私有構造器
20 private Role(String name){
21 this.name = name;
22 System.out.println("Constructor Role(String name) is invoking.");
23 }
24
25 //get and set method
26
27 public String getName() {
28 return name;
29 }
30 public void setName(String name) {
31 this.name = name;
32 }
33 public String getType() {
34 return type;
35 }
36 public void setType(String type) {
37 this.type = type;
38 }
39
40 //override the toString method to show the class
41 @Override
42 public String toString(){
43 return "This is a role called "+this.name;
44 }
45
46 }
在沒有對象實例的時候,主要有兩種辦法。
//獲得類類型的兩種方式
Class cls1 = Role.class;
Class cls2 = Class.forName("yui.Role");
注意第二種方式中,forName中的參數一定是完整的類名(包名+類名),並且這個方法需要捕獲異常。現在得到cls1就可以創建一個Role類的實例了,利用Class的newInstance方法相當於調用類的默認的構造器
Object o = cls1.newInstance(); //創建一個實例
//Object o1 = new Role(); //與上面的方法等價
這樣就創建了一個對象,缺點是我們只能利用默認構造函數,因為Class的newInstance是不接受參數的,后面會講到可接受參數的newInstance,第二,如果類的構造函數是private的,比如Class,我們仍舊不能實例化其對象。
獲取類的構造器
首先介紹一下Constructor類,這個類用來封裝反射得到的構造器,Class有四個方法來獲得Constructor對象
- public Constructor<?>[] getConstructors() 返回類中所有的public構造器集合,默認構造器的下標為0
- public Constructor<T> getConstructor(Class<?>... parameterTypes) 返回指定public構造器,參數為構造器參數類型集合
- public Constructor<?>[] getDeclaredConstructors() 返回類中所有的構造器,包括私有
- public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 返回任意指定的構造器
1 /**
2 * 獲取構造方法Constructor
3 * getConstructor() only for public
4 * getDeclaredConstructor() global access all
5 *
6 * */
7
8 //指定參數列表獲取特定的方法
9 Constructor con = cls1.getDeclaredConstructor(new Class[]{String.class});
10 con.setAccessible(true); //設置可訪問的權限
11 Object obj = con.newInstance(new Object[]{"liyang"});
12 System.out.println(obj); //打印一下這個對象的信息
13
14 //獲取所有的構造方法集合
15 Constructor con1[] = cls1.getDeclaredConstructors();
16 con1[1].setAccessible(true);
17 Object obj1 = con1[1].newInstance(new Object[]{"tom"});
18 System.out.println(obj1);
- public Field getDeclaredField(String name) 獲取任意指定名字的成員
- public Field[] getDeclaredFields() 獲取所有的成員變量
- public Field getField(String name) 獲取任意public成員變量
- public Field[] getFields() 獲取所有的public成員變量
1 /**
2 * 獲取成員變量Field
3 * getField()
4 * getDeclaredField()
5 * */
6 Field mem = cls1.getDeclaredField("name");
7 mem.setAccessible(true);
8 System.out.println("we get form field :"+mem.get(obj));
9
- public Method[] getMethods() 獲取所有的共有方法的集合
- public Method getMethod(String name,Class<?>... parameterTypes) 獲取指定公有方法 參數1:方法名 參數2:參數類型集合
- public Method[] getDeclaredMethods() 獲取所有的方法
- public Method getDeclaredMethod(String name,Class<?>... parameterTypes) 獲取任意指定方法
1 /**
2 * 調用類的方法 Method
3 * getMethod()
4 * getDeclaredMethod()
5 *
6 * */
7 Method f = cls1.getMethod("getName", null);
8 Object name = f.invoke(obj, null);
9 System.out.println("we invoke method : "+ name);
請支持Java Taste 項目:https://github.com/octobershiner/Java-Taste