Java : in what order are static final fields initialized?(Java:静态最终字段的初始化顺序是什么?)
问题描述
好的,假设我有一个看起来像这样的课程:
Okay, so say I have a class that looks like this :
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 之前实例化吗?
Can I count on the class loader to initialize those fields in order, such that I can rely on SERVLET_LOGGER to be instantiated before signupObservableAgent?
推荐答案
是的,它们按照它们在源代码中出现的顺序进行初始化.您可以在 Java 语言规范,§12.4.2.见第 9 步,内容如下:
Yes, they are initialized in the order in which they appear in the source. You can read all of the gory details in The Java Language Specification, §12.4.2. See step 9, which reads:
... 执行类的类变量初始化器和静态初始化器,或者接口的字段初始化器,按照文本顺序,就好像它们是一个单独的块一样,除了最终的类变量和接口的字段的值是编译时常量首先被初始化...
... 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:静态最终字段的初始化顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java:静态最终字段的初始化顺序是什么?
基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01