gpt4 book ai didi

java : in what order are static final fields initialized?

转载 作者:IT老高 更新时间:2023-10-28 21:00:43 25 4
gpt4 key购买 nike

好的,假设我有一个看起来像这样的类(class):

public class SignupServlet extends HttpServlet {
private static final Logger SERVLET_LOGGER=COMPANYLog.open(SignupServlet.class);
private static final ExceptionMessageHandler handler = new ExceptionMessageHandler();
private static final SignupServletObservableAgent signupObservableAgent =
new SignupServletObservableAgent(null, SERVLET_LOGGER);
}

我可以指望类加载器按顺序初始化这些字段,以便我可以依赖 SERVLET_LOGGER 在 signupObservableAgent 之前实例化吗?

最佳答案

是的,它们按照它们在源中出现的顺序进行初始化。您可以在 The Java Language Specification, §12.4.2 中阅读所有血腥细节.见第 9 步,内容如下:

... execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block, except that final class variables and fields of interfaces whose values are compile-time constants are initialized first ...

关于 java : in what order are static final fields initialized?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4446088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com