来源:https://www.cnblogs.com/wangjuns8/p/9279679.html
工具类
@Component
public class EnumUtils {
/**
* 反射获取枚举对象的值
*
* @param clazz
* @return
*/
public static List<KeyValueVo<Integer>> getEnumByClass(Class<?> clazz) {
List<KeyValueVo<Integer>> list = new ArrayList<>();
try {
Object[] objects = clazz.getEnumConstants();
Method values = clazz.getMethod("values");
IHealthEnum inter[] = (IHealthEnum[]) values.invoke(null, null);
for (IHealthEnum iHealthEnum : inter) {
KeyValueVo<Integer> result = new KeyValueVo<>();
result.setKey(iHealthEnum.getKey());
result.setValue(iHealthEnum.getValue());
list.add(result);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return list;
}
}
}
接口
public interface IHealthEnum {
Integer getKey();
Object getValue();
}
枚举类样例(需要实现 IHealthEnum 接口的两个方法 用于赋值)
@Getter
public enum HealthDictEnum implements IHealthEnum {
THIS_ENUM(0, "字典标识", "THIS", HealthDictEnum.class),
//症状
SYMPTOM_ENUM(1, "症状", "SYMPTOM", SymptomEnum.class),
;
private Integer code;
private String name;
private String type;
private Class anEnum;
HealthDictEnum(Integer code, String name, String type, Class anEnum) {
this.code = code;
this.name = name;
this.type = type;
this.anEnum = anEnum;
}
public static HashMap<Integer, String> map = new HashMap<>();
public static HashMap<Integer, Class> mapEnum = new HashMap<>();
static {
for (HealthDictEnum value : HealthDictEnum.values()) {
map.put(value.getCode(), value.getName());
mapEnum.put(value.getCode(), value.getAnEnum());
}
}
@Override
public Integer getKey() {
return code;
}
@Override
public Object getValue() {
return name;
}
}
映射的实体类
@Data
public class KeyValueVo<T> implements Serializable {
private static final long serialVersionUID = 8339478404020039733L;
private T key;
private Object value;
public KeyValueVo() {
}
public KeyValueVo(T key, Object value) {
this.key = key;
this.value = value;
}
}