Java:初始化静态最终字段的顺序是什么? [英] Java : in what order are static final fields initialized?

查看:152
本文介绍了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:初始化静态最终字段的顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆