java 枚举反射获得所有枚举定义,java反射枚举定义,首先定义一个接口,该接口
首先定义一个接口,该接口用来暴露枚举的name和value, 然后枚举从此接口继承。
NameValueEnumUtils 提供静态方法getNameValues获得枚举的值public abstract class NameValueEnumUtils { public static NameValue[] getNameValues(@SuppressWarnings("rawtypes") Class clazz) { if (!clazz.isEnum()) { throw new RuntimeException("NameValueEnumUtils can only service for enum"); } Object[] nvs = clazz.getEnumConstants(); NameValue[] result = new NameValue[nvs.length]; int i=0; for (Object obj : nvs) { result[i++] = (NameValue)obj; } return result; }}
NameValue是枚举需要实现的接口:public interface NameValue { int getValue(); String getName();}
枚举示例:public enum CheckType implements NameValue { PROCESS("进程", 1), CPU("CPU", 2), MEMORY("内存", 3), DATABASE("数据库", 4), PORT("端口", 5), REDIS("REDIS", 6), MQ("MQ", 7), DNS("DNS", 8), HTTP("HTTP", 9); private String typeName; private int typeValue; private CheckType(String name, int val) { this.typeName = name; this.typeValue = val; } public int getValue() { return this.typeValue; } public String getName() { return this.typeName; }}