反射,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類的執行個體)。
如果我們拿到一個類的類型 資訊,就可以利用反射擷取其各種成員以及方法了。(註:Class 從JDK1.5版本後就開始更多為泛型服務了) 那麼我們怎麼拿到一個類型的資訊呢?假設我們有一個Role類:
package yui; /** * A base class having some attributes and methods * @author Octobershiner * @since 2012 3 17 * * */ public class Role { private String name; private String type; // Constructors public Role(){ System.out.println("Constructor Role() is invoking"); } //私人構造器 private Role(String name){ this.name = name; System.out.println("Constructor Role(String name) is invoking."); } //get and set method public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } //override the toString method to show the class @Override public String toString(){ return "This is a role called "+this.name; } }
在沒有對象執行個體的時候,主要有兩種辦法。
//獲得類類型的兩種方式 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,我們仍舊不能 執行個體化其對象。