Java 反射機制

1. 什麼是反射?

反射(Reflection)能夠讓運行於JVM中的程序檢測和修改運行時的行爲。

2. 我們爲何需要反射?

反射能夠讓我們:

  • 在運行時檢測對象的類型;
  • 動態構造某個類的對象;
  • 檢測類的屬性和方法;
  • 任意調用對象的方法;
  • 修改構造函數、方法、屬性的可見性;
  • 以及其他。

反射示例:Class.forName()方法可以通過類或接口的名稱(一個字符串或完全限定名)來獲取對應的Class對象。forName方法會觸發類的初始化。

// 使用反射
Class<?> c = Class.forName("classpath.and.classname");
Object dog = c.newInstance();
Method m = c.getDeclaredMethod("bark", new Class<?>[0]);
m.invoke(dog);

Class c = "foo".getClass();
這返回的是String類型的class

enum E { A, B }
Class c = A.getClass();
A是枚舉類型E的實例,所以返回的是E的Class

byte[] bytes = new byte[1024];
Class c = bytes.getClass();

(官方解釋數組類型的getClass())Since arrays are Objects, it is also possible to invoke getClass() on an instance of an array. The returned Class corresponds to an array with component type byte.

Set<String> s = new HashSet<String>();
Class c = s.getClass();
這裏Set是一個接口,getClass()返回的是HashSet的class

The .class Syntax

boolean b;
Class c = b.getClass();   // compile-time error

Class c = boolean.class;  // correct

TYPE Field for Primitive Type Wrappers

Class c = Double.TYPE;

Methods that Return Classes

Class.getSuperclass()
返回指定類的super class
Class c = javax.swing.JButton.class.getSuperclass();
The super class of javax.swing.JButton is javax.swing.AbstractButton.
Class.getClasses()
返回當前類的所有public classes, interfaces, and enums
Class.getDeclaredClasses()
Returns all of the classes interfaces, and enums that are explicitly declared in this class.


Class.getEnclosingClass()
Returns the immediately enclosing class of the class.
Class c = Thread.State.class().getEnclosingClass();
The enclosing class of the enum Thread.State is Thread.
public class MyClass {
    static Object o = new Object() { 
        public void m() {} 
    };
    static Class<c> = o.getClass().getEnclosingClass();
}
The anonymous class defined by o is enclosed by MyClass.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章