最佳答案
为什么 enum 的构造函数不能访问静态字段和方法?这对类是完全有效的,但对枚举是不允许的。
我要做的是将我的枚举实例存储在一个静态 Map 中。考虑一下这个示例代码,它允许按缩写进行查找:
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);
}
}
由于枚举在其构造函数中不允许静态引用,因此这将不起作用。然而,如果它作为一个类实现,那么只需 find 就可以工作:
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
}