JavaSE 5.0中新增了對枚舉的支持,關於枚舉的用處我就不詳細說明了,簡而言之,在枚舉中可以定義常量,供程序其它部分使用。
Java中內建的枚舉類型只提供了定義枚舉名字,隱含了1,2,。 。等對應的實際值。
利用org.apache.commons.lang.enums包下ValuedEnum類型,我們可以透過擴充(extends)此類,提供更強大的功能。故名思義,ValuedEnum----就是被命名的枚舉,我們可以隨意定義枚舉的名字,此類提供了許多方法,如getEnumMap,getEnumList,interator等方法,對枚舉類別的常數進行訪問。下面是它的一個例子:
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.enums.ValuedEnum;
public final class WeekDayEnum extends ValuedEnum{
/**
*
*/
public static final long serialVersionUID = 732377557389126868L;
private static final int MONDAY=1;
private static final int TUESDAY=2;
private static final int WEDSDAY=3;
private static final int THURSDAY = 4;
private static final int FRIDAY=5;
private static final int SATDAY=6;
private static final int SUNDAY=7;
public static final WeekDayEnum WEEKDAY_MONDAY_ENUM = new WeekDayEnum("星期一",MONDAY);
public static final WeekDayEnum WEEKDAY_TUESDAY_ENUM = new WeekDayEnum("星期二",TUESDAY);
public static final WeekDayEnum WEEKDAY_WEDSDAY_ENUM = new WeekDayEnum("星期三",WEDSDAY);
public static final WeekDayEnum WEEKDAY_THURSDAY_ENUM = new WeekDayEnum("星期四",THURSDAY);
public static final WeekDayEnum WEEKDAY_FRIDAY_ENUM = new WeekDayEnum("星期五",FRIDAY);
public static final WeekDayEnum WEEKDAY_SATDAY_ENUM = new WeekDayEnum("星期六",SATDAY);
public static final WeekDayEnum WEEKDAY_SUNDAY_ENUM = new WeekDayEnum("星期日",SUNDAY);
protected WeekDayEnum(String name, int value) {
super(name, value);
}
public static WeekDayEnum getEnum(String type){
return (WeekDayEnum)getEnum(WeekDayEnum.class, type);
}
public static WeekDayEnum getEnum(int type){
return (WeekDayEnum)getEnum(WeekDayEnum.class, type);
}
public static Map getEnumMap(){
return getEnumMap(WeekDayEnum.class);
}
public static List getEnumList(){
return getEnumList(WeekDayEnum.class);
}
public static Iterator iterator(){
return iterator();
}
驅動類別中我們可以隨意呼叫其中的方法,以獲得我們想要的結果:
例如:WeekDayEnum.WEEKDAY_MONDAY_ENUM即存取了枚舉的值。
我們也可以WeekDayEnum.getEnumList傳回枚舉類別所定義的常數的集合
以及透過WeekDayEnum.getEnumMap傳回其Map鍵值對集合等。