官方给出了
@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
//私有方法,是个本地方法,直接调用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;
//测试代码
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,对于字节加载到类加载器的过程,主要体现在静态区域的初始化,测试结果也显示,会调用静态快
如果使用第二种方法,将初始参数设置为false,则不会调用静态块,从而可以得出结论,文档中所说的初始化主要是指静态块。
在这两者调用的过程中,都会去调用构造方法,也证明,构造方法主要是实例化对象的时候才会被调用,在Class中从newInstance方法就能体现出来。