문제

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?

도움이 되었습니까?

해결책

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. To test it we can change Foo like this

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. 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. According to JLS section 12.4.1, initialization occurs in these cases:

  1. T is a class and an instance of T is created.

  2. T is a class and a static method declared by T is invoked.

  3. A static field declared by T is assigned.

  4. A static field declared by T is used and the field is not a constant variable (§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.

    1. Cannot occur, as the constructor is private. 2. Cannot occur as Foo has no static methods. 3. cannot occur because the static field is private. 4. cannot occur because the static field is private and so cannot be used. 5. cannot occur because there are no assert statements.

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)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top