这个包按照说明是:Interfaces and classes for type-safe enum support on JDK >= 1.3。提供类型安全的枚举类型。代码也是相当简单,枚举类型又分为静态类型和通用类型。静态类型其实跟jdk1.5引进的enum类型类似,都是以int类型做code,比如声明一个Dog类型:
然后就可以这样声明枚举类型了:
同时有一个静态枚举类型的处理类用于提取信息:StaticLabeledEnumResolver ——这个类继承自抽象类AbstractCachingLabeledEnumResolver,而抽象类实现了接口LabeledEnumResovler,看看这个接口就知道所谓处理类是干什么的了:
StaticLabeledEnumResolver 使用了单例模式,同时AbstractCachingLabeledEnumResolver定义了一个模板法方法并使用:
所谓通用性的枚举类型,是指不定义成static,并且可以灵活使用其他类型做code的枚举,比如spring已经内置的3种:ShortCodedLabeledEnum ,StringCodeLabeledEnum和LetterCodeLabeledEnum,这些类都继承自AbstractLabeledEnum,类名已经显示了它们的用途,不再细说。这个包完整的类图如下:
public
static
class
Dog
extends
StaticLabeledEnum {
private Dog( int code, String name) {
super (code, name);
}
}
private Dog( int code, String name) {
super (code, name);
}
}
然后就可以这样声明枚举类型了:
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 " ;
}
};
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 " ;
}
};
同时有一个静态枚举类型的处理类用于提取信息:StaticLabeledEnumResolver ——这个类继承自抽象类AbstractCachingLabeledEnumResolver,而抽象类实现了接口LabeledEnumResovler,看看这个接口就知道所谓处理类是干什么的了:
public
interface
LabeledEnumResolver {
// 获取某个类中声明的枚举类型,这些类型 // 必须是LabeledEnum的子类
public Set getLabeledEnumSet(Class type) throws IllegalArgumentException;
public Map getLabeledEnumMap(Class type) throws IllegalArgumentException;
//根据code获取枚举
public LabeledEnum getLabeledEnumByCode(Class type, Comparable code) throws IllegalArgumentException;
//根据lable获取枚举
public LabeledEnum getLabeledEnumByLabel(Class type, String label) throws IllegalArgumentException;
}
// 获取某个类中声明的枚举类型,这些类型 // 必须是LabeledEnum的子类
public Set getLabeledEnumSet(Class type) throws IllegalArgumentException;
public Map getLabeledEnumMap(Class type) throws IllegalArgumentException;
//根据code获取枚举
public LabeledEnum getLabeledEnumByCode(Class type, Comparable code) throws IllegalArgumentException;
//根据lable获取枚举
public LabeledEnum getLabeledEnumByLabel(Class type, String label) throws IllegalArgumentException;
}
StaticLabeledEnumResolver 使用了单例模式,同时AbstractCachingLabeledEnumResolver定义了一个模板法方法并使用:
protected
abstract
Set findLabeledEnums(Class type);
也是一个Template Method模式应用的例子。
所谓通用性的枚举类型,是指不定义成static,并且可以灵活使用其他类型做code的枚举,比如spring已经内置的3种:ShortCodedLabeledEnum ,StringCodeLabeledEnum和LetterCodeLabeledEnum,这些类都继承自AbstractLabeledEnum,类名已经显示了它们的用途,不再细说。这个包完整的类图如下:
![spring-enum.jpg](https://i-blog.csdnimg.cn/blog_migrate/a356cfc036ee74f9623ced3c5ab72d5a.jpeg)
![109925.html](https://i-blog.csdnimg.cn/blog_migrate/755540931dba76d6153eb237e4ce40bb.jpeg)