为什么枚举的构造函数不能访问静态字段? [英] Why can't enum's constructor access static fields?

查看:24
本文介绍了为什么枚举的构造函数不能访问静态字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么枚举的构造函数不能访问静态字段和方法?这对类完全有效,但不允许用于枚举.

Why can't enum's constructor access static fields and methods? This is perfectly valid with a class, but is not allowed with an enum.

我想做的是将我的枚举实例存储在一个静态 Map 中.考虑这个允许按缩写查找的示例代码:

What I'm trying to do is store my enum instances in a static Map. Consider this example code which allows lookup by abbreivation:

public enum Day {
    Sunday("Sun"), Monday("Mon"), Tuesday("Tue"), Wednesday("Wed"), Thursday("Thu"), Friday("Fri"), Saturday("Sat");

    private final String abbreviation;

    private static final Map<String, Day> ABBREV_MAP = new HashMap<String, Day>();

    private Day(String abbreviation) {
        this.abbreviation = abbreviation;
        ABBREV_MAP.put(abbreviation, this);  // Not valid
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public static Day getByAbbreviation(String abbreviation) {
        return ABBREV_MAP.get(abbreviation);
    }
}

这将不起作用,因为枚举不允许在其构造函数中使用静态引用.然而,它只是找到是否作为类实现:

This will not work as enum doesn't allow static references in its constructor. It however works just find if implemented as a class:

public static final Day SUNDAY = new Day("Sunday", "Sun");
private Day(String name, String abbreviation) {
    this.name = name;
    this.abbreviation = abbreviation;
    ABBREV_MAP.put(abbreviation, this);  // Valid
}

推荐答案

在静态字段全部初始化之前调用构造函数,因为静态字段(包括表示枚举值的那些)是按文本顺序初始化的,而枚举值总是在其他字段之前.请注意,在您的类示例中,您没有显示 ABBREV_MAP 的初始化位置 - 如果是 after SUNDAY,则在类初始化时会出现异常.

The constructor is called before the static fields have all been initialized, because the static fields (including those representing the enum values) are initialized in textual order, and the enum values always come before the other fields. Note that in your class example you haven't shown where ABBREV_MAP is initialized - if it's after SUNDAY, you'll get an exception when the class is initialized.

是的,这有点痛苦,而且可能设计得更好.

Yes, it's a bit of a pain and could probably have been designed better.

然而,根据我的经验,通常的答案是在所有静态初始化器的末尾有一个 static {} 块,并在那里使用 EnumSet.allOf 获取所有值.

However, the usual answer in my experience is to have a static {} block at the end of all the static initializers, and do all static initialization there, using EnumSet.allOf to get at all the values.

这篇关于为什么枚举的构造函数不能访问静态字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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