简体   繁体   English

私有类上的静态最终成员初始化

[英]Static final member initialization on private class

Consider the following code: 考虑以下代码:

public final class Foo {
    private static final Random random = new Random();
    private Foo() {}
}

This class can not be instantiated so, when random is initialized? 此类无法实例化,因此何时初始化random?

Static fields are initialized during class initialization, eg here 静态字段是在类初始化期间初始化的,例如此处

    ...
    Class.forName("test.Foo");
    ...

after loading JVM will init random field, no Foo instance will be created. 加载JVM之后,它将初始化random字段,因此不会创建Foo实例。 To test it we can change Foo like this 为了测试它,我们可以像这样改变Foo

class Foo {
    private static final Random random = new Random() {
        {
            System.out.println("random initialized");
        }
    };
...

According to the Java Language Specification section 12.4 , initializing of static members and blocks takes place during class initialization. 根据Java语言规范的第12.4节 ,静态成员和块的初始化在类初始化期间进行。 The precise times when a class is initialized and the steps for doing so can be found at the link; 可以在链接上找到初始化类的确切时间以及执行初始化的步骤; in general, classes are loaded/initialized the first time they are accessed in any way, and that loading/initialization includes the creation of static members. 通常,第一次以任何方式访问类时都将加载/初始化类,并且该加载/初始化包括创建静态成员。

However, if that is all there is to Foo , I don't believe random would ever be initialized, as it cannot be instantiated, its static member cannot be accessed, and it cannot be subclassed. 但是,如果这就是Foo全部内容,那么我不相信将不会初始化random ,因为无法实例化它,无法访问其静态成员,也不能对其进行子类化。 According to JLS section 12.4.1, initialization occurs in these cases: 根据JLS第12.4.1节,在以下情况下发生初始化:

  1. T is a class and an instance of T is created. T是一个类,并创建T的实例。

  2. T is a class and a static method declared by T is invoked. T是一个类,并调用T声明的静态方法。

  3. A static field declared by T is assigned. 分配由T声明的静态字段。

  4. A static field declared by T is used and the field is not a constant variable (§4.12.4). 使用由T声明的静态字段,并且该字段不是常量变量(第4.12.4节)。

  5. T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed. T是顶级类(第7.6节),并执行词法嵌套在T中的断言(第14.10节)(第8.1.3节)。

    1. Cannot occur, as the constructor is private. 由于构造函数是私有的,因此无法发生。 2. Cannot occur as Foo has no static methods. 2.无法发生,因为Foo没有静态方法。 3. cannot occur because the static field is private. 3.不会发生,因为静态字段是私有的。 4. cannot occur because the static field is private and so cannot be used. 4.不会发生,因为静态字段是私有的,因此无法使用。 5. cannot occur because there are no assert statements. 5.不会发生,因为没有assert语句。

So I don't think random would ever be initialized, given that OP's code is all that there is (edit: unless you use reflection) 因此,鉴于OP的代码已全部存在,因此我认为不会初始化random (编辑:除非您使用反射)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM