public enum ColorEnum{
Red(0,"红"),Green(1,"绿");
private final int value;
private final String label;
ColorEnum(int value, String label){
this.value = value;
this.label = label;
}
public static ColorEnum parseFromValue(int value) throws ParseToColorEnumException{
switch(value){
case 0:
return Red;
case 1:
return Green;
default:
throw new ParseToColorEnumException("转换成颜色枚举时出错!");
}
}
public String toString(){
return this.getLabel() + ":" + this.getValue();
}
public int getValue() {
return value;
}
public String getLabel() {
return label;
}
}
public class ParseToColorEnumException extends Exception {
public ParseToColorEnumException(String message) {
super(message);
}
}
public class ColorEnumTest {
public static void main(String[] args) {
try{
//ColorEnum a = ColorEnum.parseFromValue(3);
ColorEnum colorEnum = parseFromValue(0);
switch (colorEnum) {
case Green:
System.out.println("green");
break;
case Red:
System.out.println("red");
break;
}
System.out.print(colorEnum);
}catch(Exception e){
e.printStackTrace();
}
}
}