官方給出了
@CallerSensitive
public static Class<?> forName(String className)
throws ClassNotFoundException {
Class<?> caller = Reflection.getCallerClass();
return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}
@CallerSensitive
public static Class<?> forName(String name, boolean initialize,
ClassLoader loader)
throws ClassNotFoundException
//私有方法蚌堵,是個(gè)本地方法芍秆,直接調(diào)用C JNI
/** Called after security check for system loader access checks have been made. */
private static native Class<?> forName0(String name, boolean initialize,
ClassLoader loader,
Class<?> caller)
throws ClassNotFoundException;
//測(cè)試代碼
public class ClassTest {
public static void main(String args[]) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
// Class clazz1 = A.class;
//
// System.out.println(clazz1.newInstance().getClass().getSimpleName());
//
//
// Class clazA = Class.forName("com.wd.bigdata.javaexample.proxy.Class.A");
// .getConstructor(String.class,int.class,float.class)
System.out.println("================");
Class<?> claz = Class.forName("com.wd.bigdata.javaexample.proxy.Class.A",
false,
A.class.getClassLoader());
// Object o = con.newInstance("yang",29,0.2f);
//
// System.out.println(o.getClass().getName());
// System.out.println(o.toString());
}
public class A {
private String field1;
private int field2;
private float field3;
static {
System.out.println("A static init");
}
public A() {
System.out.println(" A construct ");
}
public A(String field1) {
this.field1 = field1;
}
public A(String field1, int field2) {
this.field1 = field1;
this.field2 = field2;
}
public A(String field1, int field2, float field3) {
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
}
}
第一種通過Class.forName(name) 加載class都伪,對(duì)于字節(jié)加載到類加載器的過程,主要體現(xiàn)在靜態(tài)區(qū)域的初始化示罗,測(cè)試結(jié)果也顯示惩猫,會(huì)調(diào)用靜態(tài)快
如果使用第二種方法,將初始參數(shù)設(shè)置為false蚜点,則不會(huì)調(diào)用靜態(tài)塊轧房,從而可以得出結(jié)論,文檔中所說的初始化主要是指靜態(tài)塊绍绘。
在這兩者調(diào)用的過程中锯厢,都會(huì)去調(diào)用構(gòu)造方法,也證明脯倒,構(gòu)造方法主要是實(shí)例化對(duì)象的時(shí)候才會(huì)被調(diào)用实辑,在Class中從newInstance方法就能體現(xiàn)出來。