JLS 中是否对静态初始化块的执行顺序有任何保证?
我想知道使用如下结构是否可靠:
private static final Map<String, String> engMessages;
private static final Map<String, String> rusMessages;
static {
engMessages = new HashMap<String, String> () {{
put ("msgname", "value");
}};
rusMessages = new HashMap<String, String> () {{
put ("msgname", "значение");
}};
}
private static Map<String, String> msgSource;
static {
msgSource = engMessages;
}
public static String msg (String msgName) {
return msgSource.get (msgName);
}
是否有可能得到 NullPointerException 因为 msgSource
初始化块将在初始化 的块之前执行engMessages?
(关于为什么我不在上层 init.block 的末尾进行 msgSource
初始化:这只是品味问题;如果所描述的构造不可靠,我会这样做)
I wonder if it's reliable to use a construction like:
private static final Map<String, String> engMessages;
private static final Map<String, String> rusMessages;
static {
engMessages = new HashMap<String, String> () {{
put ("msgname", "value");
}};
rusMessages = new HashMap<String, String> () {{
put ("msgname", "значение");
}};
}
private static Map<String, String> msgSource;
static {
msgSource = engMessages;
}
public static String msg (String msgName) {
return msgSource.get (msgName);
}
Is there a possibility that I'll get NullPointerException
because msgSource
initialization block will be executed before the block which initializes engMessages
?
(about why don't I do msgSource
initialization at the end of upper init. block: just the matter of taste; I'll do so if the described construction is unreliable)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,静态初始化块保证按文本顺序执行。
来自 JLS,第 12.4 节.1:
并来自 12.4.2< /a>:
但就我个人而言,我会将所有变量声明放在开头,然后放置一个静态初始化块。我认为这更容易遵循。
Yes, static initializer blocks are guaranteed to execute in textual order.
From the JLS, section 12.4.1:
And from 12.4.2:
Personally though, I'd put all the variable declarations at the start, and then a single static initializer block. I consider that to be a lot easier to follow.