【发布时间】:2013-03-27 01:05:29
【问题描述】:
我有一个如下所示的实用程序类:
public final class MyUtils {
public static final List<String> MY_VALUES = new ArrayList<String>();
{
MY_VALUES.add("foo");
MY_VALUES.add("bar");
}
}
我从另一个班级这样称呼它:
MyUtils.MY_VALUES
如果我这样做,列表是空的,如果我调试我会看到静态块永远不会运行。
我从When does static class initialization happen? 和How to force a class to be initialised? 的答案中了解到,该块应该在a static field of the class is assigned 时运行,我马上就这样做了。我还尝试将变量设置为非最终变量以满足条件“a non-constant static field is used”。
我可以使用其他两个问题和Why doesn't my static block of code execute? 中也建议的 init 方法,但我仍然想了解为什么它一开始就不起作用,尽管我似乎已经满足了语言规范。
【问题讨论】: