前言
在專案中,會存在很多列舉,比如下面顏色和水果的列舉,COLOR[RED(1),GREEN(2),BLUE(3)],FRUIT[APPLE(4),BANANA(5),ORANGE(6)],但是問題是,如果要增加列舉型別,就會涉及修改程式碼的問題,一個比較常見的例子是,列舉生成一個列表,供前臺選擇,如果增加型別,那麼前後臺都需要進行修改。
一個思路,是將列舉項儲存在資料庫裡,專案啟動或定時重新整理列舉項。在專案中,只定義列舉型別,比如
public enum COLOR{}
public enum FRUIT{}
在介面中,使用COLOR.valueOf()就可以獲取列舉,並傳入後面的處理層了。為什麼要使用列舉呢?型別安全麼,只要可以獲取列舉,就說明前臺傳的值是正確的,即進行了範圍校驗。
程式碼
程式碼是參考了一篇文章https://www.niceideas.ch/roll…
有興趣的可以看一下。他的例子,是在一個資料庫表裡面有一張類似業務流水錶,上面有一個CODE欄位,程式碼了對記錄的不同處理,CODE很多,他不想手寫大量的if…else語句,想轉成enum進行處理(這個我還沒有相同,動態的enum也沒辦法直接在程式碼上switch case,那麼是不是他在生成的列舉上,包含了呼叫的方法)。
下面是在他程式碼之上,進行了些許的修改,便於適應我自己的業務場景。
public enum CodeInfoEnum {
LOCK(1L,1L,"LOCK_TYPE","LOCK"),UNLOCK(1L,2L,"LOCK_TYPE","LOCK");
public Long classId;
public Long infoId;
public String classCode;
public String infoCode;
CodeInfoEnum(Long classId,Long infoId,String classCode,String infoCode){
this.classId = classId;
this.infoId = infoId;
this.classCode = classCode;
this.infoCode = infoCode;
}
public static CodeInfoEnum getByInfoId(Long infoId){
return CodeInfoEnum.valueOf(infoId+"");
}
public static List<CodeInfoEnum> getByClassId(Long classId){
return Arrays.stream(CodeInfoEnum.values()).filter(item->item.classId.equals(classId)).collect(Collectors.toList());
}
public static CodeInfoEnum getByClassCodeAndInfoCode(String classCode,String infoCode){
Optional<CodeInfoEnum> opt = Arrays.stream(CodeInfoEnum.values()).filter(item->item.classCode.equals(classCode)&&item.infoCode.equals(infoCode)).findFirst();
return opt.orElse(null);
}
@Override
public String toString() {
return "CodeInfoEnum{" +
"classId=" + classId +
", infoId=" + infoId +
", classCode=`" + classCode + ``` +
", infoCode=`" + infoCode + ``` +
`}`;
}
}
public class DynamicEnumTest {
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,Class<?>[] paramClass,Object[] paramValue) {
// 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 = CodeInfoEnum.class.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
paramClass,
//new Object[] {}
paramValue
); // could be used to pass values to the enum constuctor if needed
// 4. add new value
values.add(newValue);
Object object=values.toArray((T[]) Array.newInstance(enumType, 0));
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, object);
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
public static void main(String[] args) {
//
synchronized (CodeInfoEnum.class) {
addEnum(CodeInfoEnum.class, "3", new Class<?>[]{Long.class, Long.class, String.class, String.class}, new Object[]{2L, 3L, "ActiveStatus", "Active"});
addEnum(CodeInfoEnum.class, "4", new Class<?>[]{Long.class, Long.class, String.class, String.class}, new Object[]{2L, 4L, "ActiveStatus", "Inactive"});
addEnum(CodeInfoEnum.class, "5", new Class<?>[]{Long.class, Long.class, String.class, String.class}, new Object[]{3L, 5L, "Optype", "OP1"});
addEnum(CodeInfoEnum.class, "6", new Class<?>[]{Long.class, Long.class, String.class, String.class}, new Object[]{3L, 6L, "Optype", "OP2"});
addEnum(CodeInfoEnum.class, "7", new Class<?>[]{Long.class, Long.class, String.class, String.class}, new Object[]{3L, 7L, "Optype", "OP3"});
addEnum(CodeInfoEnum.class, "8", new Class<?>[]{Long.class, Long.class, String.class, String.class}, new Object[]{3L, 8L, "Optype", "OP4"});
}
CodeInfoEnum codeInfoEnum =CodeInfoEnum.valueOf("5");
System.out.println(codeInfoEnum);
// Run a few tests just to show it works OK.
System.out.println(Arrays.deepToString(CodeInfoEnum.values()));
System.out.println("============================列印所有列舉(包括固定的和動態的),可以將資料庫中儲存的CIC以列舉的形式載入到JVM");
for(CodeInfoEnum codeInfo:CodeInfoEnum.values()){
System.out.println(codeInfo.toString());
}
System.out.println("============================通過codeId找到的列舉,用於PO轉VO的處理");
CodeInfoEnum activeStatus_Active = CodeInfoEnum.getByInfoId(3L);
System.out.println(activeStatus_Active);
System.out.println("============================通過ClassId找到的列舉列表");
List<CodeInfoEnum> activeStatusEnumList = CodeInfoEnum.getByClassId(3L);
for(CodeInfoEnum codeInfo : activeStatusEnumList){
System.out.println(codeInfo);
}
System.out.println("============================通過ClassCode和InfoCode獲取列舉,用於匯入驗證CIC合法性");
CodeInfoEnum toGetActiveStatus_Active = CodeInfoEnum.getByClassCodeAndInfoCode("ActiveStatus","Active");
System.out.println(toGetActiveStatus_Active);
System.out.println("============================通過ClassCode和InfoCode獲取列舉,輸入不存在的Code,則返回NULL");
CodeInfoEnum toGetActiveStatus_miss = CodeInfoEnum.getByClassCodeAndInfoCode("ActiveStatus","MISS");
System.out.println(toGetActiveStatus_miss);
}
}
我將專案中所有的列舉,都定義在了CodeInfoEnum中,其中包含兩部分,一部分是固定的列舉,我是預定義的,比如記錄狀態(有效|刪除),鎖定狀態(可用|鎖定)等,這些的列舉字面值是英文大寫單詞;另一部分是動態的,具有比較強的業務含義,比如倉庫管理中的庫位型別,包裝型別這些,這些的列舉字面值是數字,即資料庫中的ID。
在使用的使用,注意:
- 在和前臺互動的時候,統一使用字面值
- 在校驗的時候,使用class_code和字面值進行校驗。
- 在controller進行引數組裝的時候,將前臺傳入的字面值轉成CodeInfoEnum
- 在持久化的時候使用字面值
- 查詢的時候,將資料庫中的字面值轉化為CodeInfoEnum
上面寫的‘使用’,目前還是設想,還沒有動手實現。也是我下面準備做的。希望有看到本文的大神,如能提供寶貴意見,將不勝感激。