为什么枚举的构造函数不能访问静态字段和方法?这对于一个类是完全有效的,但对于枚举是不允许的。
我正在尝试将枚举实例存储在静态Map中。考虑下面的示例代码,它允许通过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);
}
}
这将不起作用,因为枚举不允许在其构造函数中使用静态引用。但是,它只是在实现为类的情况下才起作用:
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
}
人到中年有点甜
呼啦一阵风
慕桂英3389331
相关分类