我对以下代码片段有几个疑问:
public class Configuration
{
public static String TEMP_DIR;
public static List<String> LEvents;
......//some more public static members......
static{
//logic to fill all the members of this class
}
}
- 我想知道填充成员的逻辑什么时候执行?
- 如果我使用实际的静态方法来执行逻辑并调用一次,这种方法是否有所不同?
最佳答案
static {
//logic to fill all the members of this class
}
代码被称为 static initializer .
I am wondering when will the logic which fills the members be executed?
Java 语言规范说
A static initializer declared in a class is executed when the class is initialized (§12.4.2).
然后你问
And is this approach different if i would have used actual static method to execute the logic and call it once?
使用静态初始化程序,JVM 负责执行代码。使用静态
方法,您必须自己调用它。为了使其等效,您可能还想保证该方法仅被调用/执行一次。
关于java类没有任何方法,但在static关键字下包含逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22874123/