在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;
}
}
这很好,因为现在我的enum有一个很好的人类可读的标签,这个标签在正常情况下是不可更改的。例如,我不能这样做:MealType.BREAKFAST.label = "fred"
然而,当我尝试在Groovy中做同样的事情时,getter和setter是自动生成的。现在我已经创建了不需要的方法。MealType.BREAKFAST.label = "fred"
将导致enum标签被改变。
将标签声明为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;
}
}