這個(gè)包按照說(shuō)明是:Interfaces and classes for type-safe enum support on JDK >= 1.3。提供類(lèi)型安全的枚舉類(lèi)型。代碼也是相當(dāng)簡(jiǎn)單,枚舉類(lèi)型又分為靜態(tài)類(lèi)型和通用類(lèi)型。靜態(tài)類(lèi)型其實(shí)跟jdk1.5引進(jìn)的enum類(lèi)型類(lèi)似,都是以int類(lèi)型做code,比如聲明一個(gè)Dog類(lèi)型:
public static class Dog extends StaticLabeledEnum {
private Dog(int code, String name) {
super(code, name);
}
}
然后就可以這樣聲明枚舉類(lèi)型了:
public static final Dog BORDER_COLLIE = new Dog(13, "Border Collie");
public static final Dog WHIPPET = new Dog(14, "Whippet");
public static final Dog GOLDEN_RETRIEVER = new Dog(11, null) {
// must set type to be recognized as a "Dog"
public Class getType() {
return Dog.class;
}
public String getLabel() {
return "Golden Retriever";
}
};
同時(shí)有一個(gè)靜態(tài)枚舉類(lèi)型的處理類(lèi)用于提取信息:StaticLabeledEnumResolver
——這個(gè)類(lèi)繼承自抽象類(lèi)AbstractCachingLabeledEnumResolver,而抽象類(lèi)實(shí)現(xiàn)了接口LabeledEnumResovler,看看這個(gè)接口就知道所謂處理類(lèi)是干什么的了:
public interface LabeledEnumResolver {
//獲取某個(gè)類(lèi)中聲明的枚舉類(lèi)型,這些類(lèi)型 //必須是LabeledEnum的子類(lèi)
public Set getLabeledEnumSet(Class type) throws IllegalArgumentException;
public Map getLabeledEnumMap(Class type) throws IllegalArgumentException;
//根據(jù)code獲取枚舉
public LabeledEnum getLabeledEnumByCode(Class type, Comparable code) throws IllegalArgumentException;
//根據(jù)lable獲取枚舉
public LabeledEnum getLabeledEnumByLabel(Class type, String label) throws IllegalArgumentException;
}
StaticLabeledEnumResolver
使用了單例模式,同時(shí)AbstractCachingLabeledEnumResolver定義了一個(gè)模板法方法并使用:
protected abstract Set findLabeledEnums(Class type);
也是一個(gè)Template Method模式應(yīng)用的例子。
所謂通用性的枚舉類(lèi)型,是指不定義成static,并且可以靈活使用其他類(lèi)型做code的枚舉,比如spring已經(jīng)內(nèi)置的3種:ShortCodedLabeledEnum
,StringCodeLabeledEnum和LetterCodeLabeledEnum,這些類(lèi)都繼承自AbstractLabeledEnum,類(lèi)名已經(jīng)顯示了它們的用途,不再細(xì)說(shuō)。這個(gè)包完整的類(lèi)圖如下: