Pergunta

I noticed something in static initializers which may be a bug in the javac. I have constructed a scenario where I can assign a variable a value but not read that value back.

The two examples are below, the first compiles fine, the second gets an error when trying to read a value from tmp, but for some reason assigning a value to tmp is permitted. I could understand if it could neither read nor write to the variable since tmp is declared after the static initializer, but an error on only one of those does not make sense to me.

//Compiles Successfully:
public class Script
{
    public static Object tmp;
    static
    {
        tmp = new Object();
        System.out.println(tmp);
    }

}

//error only on the read but not the assignment
public class Script
{

    static
    {
        tmp = new Object();
        System.out.println(tmp);
    }
    public static Object tmp;
}

to emphasize the point further, this does compile successfully.

public class Script
{

    static
    {
        tmp = new Object();
    }
    public static Object tmp;
}
Foi útil?

Solução

It seems this is defined in the spec (See JLS 8.3.2.3):

The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:

  • The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer
    of C.

  • The usage is not on the left hand side of an assignment.

  • The usage is via a simple name.

  • C is the innermost class or interface enclosing the usage.

So if the usage is on the left hand side of an assignment, then it is legal, since the second one does not hold anymore.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top