反射(Reflection)是Java被視爲動態(或準動態)語言的一個關鍵性質。這個機制允許程序在運行時通過Reflection APIs取得任何一個已知名稱的class的內部信息,包括其modifiers(諸如public, static 等等)、superclass(例如Object)、實現的interfaces,也包括field(屬性)和methods(方法)的所有 信息,並可於運行時改變fields內容或調用 Constructor,methods。
什麼是反射,簡單地說,就是在程序運行是來檢查已知名稱的Class中的內部信息,那麼動態和反射又是什麼關係呢。從某種程度上講,動態是依靠反射來實現的。
以上簡單的文字描述應該已經可以爲動態與反射下個粗略的定義,讓人瞭解大概是個什麼東東。接下來更進一步具體分析,就得來看看簡單的代碼示例。
這是靜態綁定的情況:
// 靜態編譯/靜態綁定
IVehicle vehicle = new BMW();
vehicle.forward(100);
這種情況不必多說,下面來看看動態綁定的情況:
// 動態編譯/綁定/運行時多態
// 1.載入類對象
Class c = Class.forName("ref.BMW");
// 2.調用默認無參構造器生成對象
Object object = c.newInstance();
// 3.強制轉型
IVehicle ve = (IVehicle) object;
ve.forward(500);
從這裏我們就來看動態綁定和靜態綁定之間的區別。靜態綁定在編譯的過程中就會進行檢驗,假設找不到BMW這個類,編譯就會出錯。而動態綁定的時候,如果找不到這個類,是否也會出錯呢?答案是否定的,這個時候是能夠通過編譯的。但是在運行時,會拋出一個ClassNotFoundException。
那麼反射又是怎麼一會事呢,簡單的說就是根據類名得到類的內部信息。下面就是反射的一些簡單代碼示例。
// 得到類名
String className = c.getName();
System.out.println("className:" + className);
// 得到類中的方法對象數組
java.lang.reflect.Method[] methods = c.getMethods();
for (int i = 0; i < methods.length; i++) {
System.out.println("methods:" + methods[i].getName());
}
// 得到類定義的構造對象數組
java.lang.reflect.Constructor[] cons = c.getConstructors();
for (int i = 0; i < cons.length; i++) {
System.out.println("cons:" + cons[i].getName());
}
// 得到類定義的屬性對象數組
java.lang.reflect.Field[] fields = c.getFields();
for (int i = 0; i < fields.length; i++) {
System.out.println("fields:" + fields[i].getName());
}
// 得到類的直接父類對象
Class superClass = c.getSuperclass();
System.out.println("superClass:" + superClass.getName());
// 得到類所有實現的接口類對象數組
Class[] interfaces = c.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
System.out.println("interfaces:" + interfaces[i].getName());
}
下面來看看輸出。
className:ref.BMW
methods:forward
methods:startMe
methods:getEnergy
methods:wait
methods:wait
methods:wait
methods:hashCode
methods:getClass
methods:equals
methods:toString
methods:notify
methods:notifyAll
cons:ref.BMW
cons:ref.BMW
fields:company
fields:energy
superClass:java.lang.Object
interfaces:ref.IVehicle
這就是所謂的反射了。當然,這裏只是列舉了一小部分,反射的功能遠非這些,其應用和所帶來的便利也不是一下子能說盡的。這裏只是作爲一個菜鳥對動態和反射提出了一些自己的理解罷了。