標籤:
要講反射,我們必須要弄清楚Class Object,因為反射提供的方法都是Class Object提供的。
下面是java.lang.Class的類注釋:
Instances of the class Class represent classes and interfaces in a running Java application.
An enum is a kind of class and an annotation is a kind of interface.
Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions.
The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the、
defineClass method in the class loader
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/Class.java
java.lang.Class代表的就是運行時載入的所有類型,包括類或者介面的執行個體。Class對象由Jvm產生(詳見 JavaScipt 實現物件導向編程的原理一文,如何控制建立類型一個意思)。下面我們就JVM 如何載入(建立)一個類的過程做個大概的說明:
假設我們運行了 Java path/to/sth.class 這個檔案(含main函數), 這時
1. JVM 初始化:
java程式回去找到jvm實現(如windows系統則為jvm.dll),並初始化jvm.
2. Class Load的初始化:
JVM完成初始化後,運行BootStrapLoader(c語言),這個類會先後建立2個Java 版本的Class Loader:ExtClassLoader(Sys Level ext Path) 與AppClassLoader (App Level Path)( 具體過程,我們之後在JVM會陸續道來)。
然後將ExtClassLoader 的Parent設定為自己(BootStrap Loader),把 AppClassLoader的Parent設定為ExtClassLoader,完成ClassLoader的
繼承關係。這個繼承關係的作用在於,JVM實現的Load Class 方法依照繼承關係進行,首先交由Parent Load進行Load,如果找不到Class,才會自己
去找。這樣也避免了重複載入的狀況。(當然我們有辦法讓一個Class在相同的JVM被載入2次,但是還沒想到用處)
3. 通過Class Loader的機制去Load sth.class。因為BootStrap Load,ExtClassLoader都找不這個類,最後交個AppClassLoader去找找到了,進行Load。
運行。
這裡一下各個Class Loader尋找路徑:
BootStrap Loader的ClassPath路徑為System.getProperty(“sun.boot.class.path”)
ExtClassLoader的Class Path 路徑為System.getProperty(“java.ext.dirs”)。
AppClassLoader的ClassPath即為System.getProperty(“java.class.path”)。
我們常常通過Classpath來配置環境變數指定,所以記得加個.在Classpath裡面哦。當然也可以通過-cp來覆蓋這個path。
所以,如果你Java 運行一個Class 出現ClassNotFoundException的話,就用上面的邏輯縷縷。
Java Reflect (Java初級)