从静态块或方法初始化静态final int并在注释中使用它

时间:2014-09-09 15:44:39

标签: java spring junit testng

我有以下Foo测试类和Bar测试类文件

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
  }
}

当我尝试编译这两个类时,Bar正确编译,但是Foo类说应该为超时分配一个常量值,有人可以解释一下原因吗?

2 个答案:

答案 0 :(得分:4)

注释属性只能分配constant expressions(以及few other types)。

Foo

public static final int timeLimit;

static{
    timeLimit=10000;
}

@Test(timeOut=timeLimit)

变量timeLimit不是常量表达式。

答案 1 :(得分:1)

我怀疑这是因为原始public static final字段实际上是由编译器在从另一个类引用时内联的。如果你必须加载另一个类来接收它,编译器就不能这样做。

我遗憾地在JLS中隐含地发现了这一点:

  

请注意,作为常量变量的静态字段(§4.12.4)是   在其他静态字段之前初始化(第12.4.2节)。这也适用于   接口(第9.3.1节)。永远不会观察到这样的领域   默认初始值(§4.12.5),即使是狡猾的程序。

显然,如果必须在其他静态字段之前初始化它们,则无法在静态块中初始化它们。

相关问题