在java中,我通常会设置一个enum
,如下所示
public enum MealType {
BREAKFAST("Breakfast"),
LUNCH("Lunch"),
DINNER_OPEN("Dinner Cafeteria Open"),
DINNER_CLOSED("Dinner Cafeteria Closed");
private String label;
private MealType(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
这很好用,因为现在我的枚举有一个很好的人类可读标签,而且在正常情况下该标签是不可更改的。例如,我做不到:MealType.BREAKFAST.label = "fred"
但是,当我尝试在Groovy中执行相同的操作时,会自动生成getter和setter。现在我创建了不需要的方法。 MealType.BREAKFAST.label = "fred"
会导致枚举标签发生变化。
答案 0 :(得分:3)
将标签声明为final
以防止生成setter:
enum MealType {
BREAKFAST("Breakfast"),
LUNCH("Lunch"),
DINNER_OPEN("Dinner Cafeteria Open"),
DINNER_CLOSED("Dinner Cafeteria Closed");
final String label;
MealType(String label) {
this.label = label;
}
}