Class.forName()和ClassLoader.loadClass()差別?
Class.forName():将類的.class檔案加載到jvm中,并且對類進行解釋,執行類中的static塊;
ClassLoader.loadClass():隻會将.class檔案加載到jvm中,不會執行static中的内容,但是在newInstance會去執行static塊。
public void test12(){
ClassLoader classLoader = Test.class.getClassLoader();
try {
Class<?> person = classLoader.loadClass(Person.class.getName()); //1
Class.forName(Person.class.getName()); //2
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public class Person {
static {
System.out.println("static Person...."); }
}
執行1 處沒有輸出。
執行2處 輸出 static Person....。
請注意!
Class.forName(name, initialize, loader)函數第二個參數可以指明是否加載static塊,并且隻有調用了newInstance()方法采用調用構造函數,建立類的對象 。
參數:
name 類型全限定名
initialize 是否初始化static true:初始化 false 不初始化static
loader 類加載器
public void test12(){
ClassLoader classLoader = Test.class.getClassLoader();
try {
Class<?> person = classLoader.loadClass(Person.class.getName()); //1
Class.forName(Person.class.getName()); //2
Class.forName(Person.class.getName(),true,classLoader); //3
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
但是當class.forname 和Class.forName(...)同時出現在一個方法時,static隻會初始化一次。
也就說在2處列印了 “static person....” 3處就不會有輸出。