参考原文:https://blog.csdn.net/jianggujin/article/details/70886606
Java静默加载
新建任意含有静态代码块的Class:
package com.ckk.test;
public class Class1 {
static {
System.out.println("static code block");
}
}
新建测试类Test:
package com.ckk.test;
public class Test {
public static void main(String[] args) throws ClassNotFoundException {
//1.Class.forName(String name)会触发静态代码块
Class<?> clazz1 = Class.forName("com.ckk.test.Class1");
System.out.println("1."+clazz1.getName());
//2.ClassLoader的loadClass(String name)方法进行加载,该方法仅会加载类而不会触发静态代码块
Class<?> clazz2 = Thread.currentThread().getContextClassLoader().loadClass("com.ckk.test.Class1");
System.out.println("2."+clazz2.getName());
//3.Class.forName(String name, boolean initialize, ClassLoader loader)重写方法中,initialize参数设为false,也不会触发静态代码块
Class<?> clazz3 = Class.forName("com.ckk.test.Class1",false,Thread.currentThread().getContextClassLoader());
System.out.println("3."+clazz3.getName());
}
}
运行Test,console结果如下:
static code block
1.com.ckk.test.Class1
===========================================================
2.com.ckk.test.Class1
===========================================================
3.com.ckk.test.Class1
网友评论