java枚举的集中管理
一、 产品中遇到的实际情况枚举类泛滥
这个
这个
这个
这个
在 JDK 1.5 之前没有枚举类型,那时候一般用接口常量来替代。而使用 Java 枚举类型 enum 可以更贴近地表示这种常量。但是在项目中,就变成这样了
二、 如何实现统一管理枚举
整体思路就是让枚举的类变少,只存在被抽象出来的几个类型的枚举类,在需要使用的地方动态的构建为所需要的枚举类型赋予对应的值,就可以了
三、 对枚举进行抽象
其实多注意看一些枚举类型,就是 单值类型的,多值类型的,还有一些复杂类型的,这里定义了三种类型的枚举,单值类型的,多值类型String Int key,String value类型的,可以根据需要进行增加
/**
- enum type is singal value
- @author yuyang
*/
public enum SingalEnum {
;
}
/**
- enum type is int key String value
- @author yuyang
*/
public enum ISEnum {
;
private final int key;
private final String value;
private ISEnum(int key, String value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public String getValue() {
return value;
}
}
/**
*
- enum type is String key String value
- @author yuyang
*/
public enum SSEnum {
;
private final String key;
private final String value;
SSEnum(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
四、 动态构建枚举值
/**
*
- @author yuyang
*/
public class EnumBuilderTools {
public static ObjectMapper mapper = JsonUtil.objectMapper();
/**
* init enums jsonmap
*/
private static Map<String, Object> singalenumsjsonMap = null;
private static Map<String, Object> isenumsjsonMap = null;
static {
try {
InputStream singalenumsins = EnumBuilderTools.class.getClassLoader().getResourceAsStream("singalenums.json");
InputStream isenumsins = EnumBuilderTools.class.getClassLoader().getResourceAsStream("isenums.json");
singalenumsjsonMap = mapper.readValue(singalenumsins, Map.class);
isenumsjsonMap = mapper.readValue(isenumsins, Map.class);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 构建但单值型枚举
*
* @param SingalEnumKey
*/
public static void buildSingalEnum(String SingalEnumKey) {
ArrayList<String> arrys = (ArrayList<String>) singalenumsjsonMap.get(SingalEnumKey);
for (int i = 0; i < arrys.size(); i++) {
DynamicEnumUtil.addEnum(SingalEnum.class, arrys.get(i).toString());
}
}
/**
* 构建ISEnum
*
* @param ISEnumKey
*/
public static void buildISEnum(String ISEnumKey) {
ArrayList<Map<String, String>> arrys = (ArrayList<Map<String, String>>) isenumsjsonMap.get(ISEnumKey);
for (int i = 0; i < arrys.size(); i++) {
Map<String, String> isenumValuemap = arrys.get(i);
DynamicEnumUtil.addEnum(ISEnum.class, isenumValuemap.get("enumName"), new Class[] { int.class, String.class }, new Object[] { Integer.valueOf(isenumValuemap.get("key")), isenumValuemap.get("value").toString() });
}
}
public static void main(String[] args) {
buildSingalEnum("ClaimType");
System.out.println(SingalEnum.valueOf("CHECKClAIM"));
System.out.println(Arrays.deepToString(SingalEnum.values()));
buildISEnum("InsuranceCompanyType");
System.out.println(Arrays.deepToString(ISEnum.values()));
System.out.println(ISEnum.valueOf("PingAn").getKey());
System.out.println(ISEnum.valueOf("PingAn").getValue());
ISEnum insuranceCompanyType = ISEnum.creator(String.valueOf(3));
System.out.println(insuranceCompanyType);
}
}
这是创建所需的枚举类型的代码
动态枚举工具类是借鉴了大神的代码
/**
- 动态枚举工具类
- @author yuyang
*/
public class DynamicEnumUtil {
private static ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory();
private static void setFailsafeFieldValue(Field field, Object target, Object value) throws NoSuchFieldException, IllegalAccessException {
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
fa.set(target, value);
}
private static void blankField(Class<?> enumClass, String fieldName) throws NoSuchFieldException, IllegalAccessException {
for (Field field : Class.class.getDeclaredFields()) {
if (field.getName().contains(fieldName)) {
AccessibleObject.setAccessible(new Field[] { field }, true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass) throws NoSuchFieldException, IllegalAccessException {
blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK
// 1.5/6
blankField(enumClass, "enumConstants"); // IBM JDK
}
private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes) throws NoSuchMethodException {
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return reflectionFactory.newConstructorAccessor(enumClass.getDeclaredConstructor(parameterTypes));
}
private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes, Object[] additionalValues) throws Exception {
Object[] parms = new Object[additionalValues.length + 2];
parms[0] = value;
parms[1] = Integer.valueOf(ordinal);
System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);
return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));
}
/**
* Add an enum instance to the enum class given as argument
*
* @param <T> the type of the enum (implicit)
* @param enumType the class of the enum to be modified
* @param enumName the name of the new enum instance to be added to the class.
*/
@SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType)) {
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
}
// 1. Lookup "$VALUES" holder in enum class and get previous enum
// instances
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(enumType, // The target enum class
enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
values.size(), new Class<?>[] {}, // could be used to pass
// values to the enum
// constuctor if needed
new Object[] {}); // could be used to pass values to the
// enum constuctor if needed
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* Add an enum instance to the enum class given as argument
*
* @param <T> the type of the enum (implicit)
* @param enumType the class of the enum to be modified
* @param enumName the name of the new enum instance to be added to the class.
*/
@SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName, Class<?>[] additionalTypes, Object[] additionalValues) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType)) {
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
}
// 1. Lookup "$VALUES" holder in enum class and get previous enum instances
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(enumType, enumName, values.size(), additionalTypes, additionalValues);
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private static enum TestEnum {
a, b, c;
};
public static void main(String[] args) {
// Dynamically add 3 new enum instances d, e, f to TestEnum
addEnum(TestEnum.class, "d");
addEnum(TestEnum.class, "e");
addEnum(TestEnum.class, "f");
// Run a few tests just to show it works OK.
System.out.println(Arrays.deepToString(TestEnum.values()));
// Shows : [a, b, c, d, e, f]
addEnum(ResponseCode.class, "TESET", new Class[] { int.class, String.class }, new Object[] { 250, "二百五" });
System.out.println(Arrays.deepToString(ResponseCode.values()));
System.out.println(ResponseCode.valueOf("TESET").getDesc());
System.out.println(ResponseCode.valueOf("TESET").getCode());
}
}