为什么枚举的构造函数无法访问静态字段?
为什么枚举的构造函数无法访问静态字段和方法?这在类中是完全有效的,但对于枚举是不允许的。
我正在尝试做的是将我的枚举实例存储在静态映射中。请考虑以下允许通过缩写进行查找的示例代码:
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);
}
}
这将不起作用,因为枚举不允许在其构造函数中使用静态引用。然而,它的工作原理只是发现如果实现为一个类:
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
}