枚举 - 静态初始化顺序 [英] Enum - static initialization order

查看:125
本文介绍了枚举 - 静态初始化顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

enum 类的构造函数中,访问 static 类是不允许的。为什么在枚举中静态初始化的顺序没有交换?



正确的代码示例:

 枚举测试
{
TEST1,TEST2;

static int x;
}

为什么java的开发人员没有创建正确的代码:

 枚举测试
{
static int x;

TEST1,TEST2;
}

然后 static 可以在构造函数中使用。现在是被禁止的。



它有什么理由还是只是他们的设计?

解决方案嗯,这是为了确保安全的实例初始化 - 枚举实例与枚举类的 static final 实例非常相似,语言已经定义了它们将被初始化。



但是,如果你知道一两招,你可以在枚举构造函数中有效地使用静态变量:

 枚举测试{
TEST1,TEST2;

static class Holder {
static int x;
}

Test(){
Holder.x ++; //没有编译器错误
}
}

有关详细信息,请参阅初始化按需支持者成语


Accessing static variables in constructor of enum class is forbidden in java. Why in enumerations the order of static initialization is not swapped?

Example of correct code:

enum Test
{
    TEST1, TEST2;

    static int x;
}

Why do developers of java did not created such code as correct:

enum Test
{
    static int x;

    TEST1, TEST2;
}

Then static variables could be used in constructor. Now it is forbidden.

Does it have any reason or it is just their design?

解决方案

Well, it's to ensure safe instance initialization - the enum instances are very similar to static final instances of the enum class, and the language has defined that they be initialized first.

But if you know a trick or two you can effectively use static variables in an enum constructor:

enum Test {
    TEST1, TEST2;

    static class Holder {
        static int x;
    }

    Test() {
        Holder.x++; // no compiler error
    }
}

For more info see Initialization-on-demand holder idiom

这篇关于枚举 - 静态初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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