类加载时机

启动main方法时
创建类的实例
创建子类的实例
访问类的静态方法
反射 Class.forName()

-XX:+TraceClassLoading

在vm option中加入此命令,在类加载时会打印日志
image.png

加载代码示例

此处仅编写了部分加载方式,其他方式请自行尝试

@RequestMapping(value = "/test1", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=utf-8")
public String test1() {
    try {
        Class c = Class.forName("com.example.demo.my.view.postConstruct.MyClass");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return "test1";
}

@RequestMapping(value = "/test2", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=utf-8")
public String test2() {
    Class c = MyClass.class;
    return "test2";
}

@RequestMapping(value = "/test3", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=utf-8")
public String test3() {
    MyClass c = new MyClass();
    return "test3";
}

打印结果

image.png


老污的猫
30 声望5 粉丝

« 上一篇
Java 后期绑定
下一篇 »
缓存一致性