Java基礎(三)反射和Class
阿新 • • 發佈:2019-01-02
一、簡介
Java反射是Java被視為動態語言的一個關鍵性質,這個機制允許程式在執行時透過Reflection APIs取得任何一個已知名稱的class的內部資訊,包括其modifiers(諸如public, static 等)、superclass(例如Object)、實現之interfaces(例如Cloneable),也包括fields和methods的所有資訊,並可於執行時改變fields內容或喚起methods。
二、原理
反射找到類資訊的過程:
1)通過類的全限定名可以找到該類的Class物件;
2)通過Class物件可以查到該類的方法、成員變數等資訊,最底層呼叫的是native方法查詢clss檔案中的內容;
3)如果Class物件的ReflectionData資料體為空,則從JVM中獲取;
Class物件:Class<?> refClass = Class.forName("test.ReflectionTest”);
// Class物件中的ReflectionData static class ReflectionData<T> { volatile Field[] declaredFields; volatile Field[] publicFields; volatile Method[] declaredMethods; volatile Method[] publicMethods; volatile Constructor<T>[] declaredConstructors; volatile Constructor<T>[] publicConstructors; volatile Field[] declaredPublicFields; volatile Method[] declaredPublicMethods; final int redefinedCount; ReflectionData(int redefinedCount) { this.redefinedCount = redefinedCount; } }