java - 类加载、静态 block

标签 java static classloader

我有这段代码,我使用 -verbose:class 选项运行它来查看已加载的类。令我惊讶的是,它显示它加载了类 A1 和 A2,但静态 block 没有被调用。

有人可以解释一下这种行为

package P1;



import java.lang.reflect.InvocationTargetException;

public class DemoReflection {

    static {
        System.out.println("Loading Demo");
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException,
            InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        System.out.println("A2 " + A2.class.getClassLoader().getClass());
        System.out.println("Demo " + DemoReflection.class.getClassLoader().getClass());
        System.out.println("A1 " + A1.class.getClassLoader().getClass());
    }

}

class A1 {
    static {
        System.out.println("Loading A1");
    }
}

class A2 extends A1 {

    static {
        System.out.println("Loading A2");
    }

    public A2() {
        System.out.println("m2");
    }

    public void m1() {
        System.out.println("m1");
    }
}

class A3 {

    static int a3Id = 3;

    static {
        System.out.println("Loading A3");
    }

}

输出:enter image description here

最佳答案

JLS §8.7说:

A static initializer declared in a class is executed when the class is initialized (§12.4.2).

那么初始化是什么意思呢?我们引用JLS §12.4.2 。这描述了详细的初始化过程。不过点JLS §12.4.1放在这里可能更合适。它说:

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
  • 这些选项都不适用于您的情况,因此不会调用静态 block 。

    关于java - 类加载、静态 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57058978/

    相关文章:

    java.lang.NoClassDefFoundError : loginpackage/LoginServlet (wrong name: WEB-INF/classes/loginpackage/LoginServlet)

    c++ - Visual C++ Express 2008 的静态运行时库链接

    我可以通过在C语言中调用函数来初始化静态全局变量吗?

    c - 使用静态变量时出错

    java - 有没有关于加载时间字节码转换而不在java命令行中指定javaagent选项的解决方案

    Java 或任何其他语言 : Which method/class invoked mine?

    java - 尝试在空对象引用上调用虚拟方法

    java - 如果未在字符串的 @Column 注释上指定长度属性,会发生什么情况

    Java_通过 getter 填充数组

    java - ThreadLocals 和并行类加载的效果