简体   繁体   中英

Initializing a static final int from static block or method and using it in annotations

I have the following Foo test class and Bar test class files

public class Foo{

  public static final int timeLimit;

  static{
    timeLimit=10000;
  }

  @Test(timeOut=timeLimit)
  public void fooTest{
    //timeout annotation is just used to specify the 
    //maximum execution time for this test method
  }
}


public class Bar{

  public static final int timeLimit=10000;

  @Test(timeOut=timeLimit)
  public void barTest{
    //timeout annotation is just used to specify the 
    //maximum execution time for this test method
  }
}

when I try to compile these two classes Bar compiles properly, but Foo class says that timeout should be assigned a constant value, can some one explain why?

Annotation attributes can only be assigned constant expressions (and a few other types ).

In Foo

public static final int timeLimit;

static{
    timeLimit=10000;
}

@Test(timeOut=timeLimit)

the variable timeLimit is not a constant expression.

I suspect it's because primitive public static final fields are actually inlined by the compiler when referenced from another class. If you have to load the other class for it to receive a value, the compiler can't do this.

I only found this implicitly in the JLS unfortunately:

Note that static fields that are constant variables (§4.12.4) are initialized before other static fields (§12.4.2). This also applies in interfaces (§9.3.1). Such fields will never be observed to have their default initial values (§4.12.5), even by devious programs.

Clearly if they have to be initialized before other static fields, they can't be initialized in static blocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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