简体   繁体   English

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

[英]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 我有以下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
  }
}

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? 当我尝试正确编译这两个类时,Bar会正确编译,但是Foo类说应该为超时分配一个恒定值,有人可以解释为什么吗?

Annotation attributes can only be assigned constant expressions (and a few other types ). 注释属性只能分配常量表达式 (和其他一些类型 )。

In Foo Foo

public static final int timeLimit;

static{
    timeLimit=10000;
}

@Test(timeOut=timeLimit)

the variable timeLimit is not a constant expression. 变量timeLimit不是常数表达式。

I suspect it's because primitive public static final fields are actually inlined by the compiler when referenced from another class. 我怀疑这是因为原始public static final字段实际上是在从另一个类引用时由编译器内联的。 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: 不幸的是,我仅在JLS中隐式地发现了这一点:

Note that static fields that are constant variables (§4.12.4) are initialized before other static fields (§12.4.2). 请注意,作为常量变量的静态字段(第4.12.4节)在其他静态字段(第12.4.2节)之前被初始化。 This also applies in interfaces (§9.3.1). 这也适用于接口(第9.3.1节)。 Such fields will never be observed to have their default initial values (§4.12.5), even by devious programs. 即使使用vious回的程序,也永远不会观察到此类字段具有其默认初始值(第4.12.5节)。

Clearly if they have to be initialized before other static fields, they can't be initialized in static blocks. 显然,如果必须在其他静态字段之前对其进行初始化,则无法在静态块中对其进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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