typetools / checker-framework

Pluggable type-checking for Java
http://checkerframework.org/
Other
1.02k stars 353 forks source link

Constructor should not assume static fields are initialized #556

Open mernst opened 8 years ago

mernst commented 8 years ago

Before the constructor is invoked, static initializers and static blocks are executed. This suggests that the Initialization Checker can assume that static fields are initialized in the constructor.

However, if any user-defined code -- including callbacks such as executions of equals() and hashCode() -- appears in a static initializer or static block, then static fields cannot be assumed to be initialized within the constructor.

A minimal test case appears in checker-framework/checker/tests/initialization/fbc/Issue556a.java , and a longer test case with explanations appears in checker-framework/checker/tests/initialization/fbc/Issue556b.java .

Thanks to Ed Price for pointing out the issue and supplying an initial test case.

mernst commented 8 years ago

Within any method, if the receiver is underinitialization (an example is the constructor), that should apply to static fields as well as to instance fields. Static method calls should be prohibited too.

It's OK to assume static fields are initialized in all methods that have an initialized receiver.

wmdietl commented 6 years ago

A possibly related problem is exhibited in this code:

public class StaticInit {
    static String a = "";

    static String b;

    static {
        b.toString();
    }

    static {
        b = "";
    }

    public static void main(String[] args) {
    }
}

The Nullness Checker issues no errors for this code, but the dereference of b causes an NPE.