枚举要对前端提供接口,提供一个自动装配的工具
1、建model对枚举包装一下
public class EnumBody {
public String label;
public Object value;
public String desc;
public EnumBody() {
}
public EnumBody(String label, Object value) {
this.label = label;
this.value = value;
}
public EnumBody(String label, Object value, String desc) {
this.label = label;
this.value = value;
this.desc = desc;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
2、定义枚举,每个枚举有个label的字段用于显示
public enum AlertType {
OFFLINE("表下线"),
MODIFY("表变更"),
EXPIRE("表到期"),
;
public String label;
AlertType(String label) {
this.label = label;
}
public String getLabel() {
if(label == null || label.length() == 0){
label = this.name();
}
return label;
}
}
3、用枚举生成EnumBody的集合
private <E extends Enum> List<EnumBody> getEnumBodies(Class<E> enumClass){
List<EnumBody> datas = new ArrayList<>();
Enum[] es = enumClass.getEnumConstants();
if(es == null || es.length == 0){
return datas;
}
for (Enum e : es) {
EnumBody body = new EnumBody();
body.setValue(e.name());
body.setLabel(e.name());
String label = getLabel(enumClass, e);
if(label != null && label.length() > 0){
body.setLabel(label);
}
datas.add(body);
}
return datas;
}
private <E extends Enum> String getLabel(Class<E> enumClass, Enum e){
try {
Field lableField = enumClass.getDeclaredField("label");
if(lableField == null){
return null;
}
Object fieldValueObject = lableField.get(e);
if(fieldValueObject == null){
return null;
}
return fieldValueObject.toString();
} catch (NoSuchFieldException ex) {
return null;
} catch (IllegalAccessException ex) {
return null;
}
}
5、调用
List<EnumBody> datas = getEnumBodies(AlertType.class);
网友评论