java枚举是为了定义缬方焱蜱一些字典数据,便于数据类型的判断等。枚举的类型直接初始化方法大家都知道,那么怎么动态添加枚举类型呢?下面我举一个星期的枚举给大家介绍我将在最后一步贴上代码供大家copy
工具/原料
jdk
ide
方法/步骤
1、查询数据库数据,这里我直接初始化一个List集合
2、创建EnumDemo类
3、新增动态添加枚举类型的公共方法,我将在最后一步贴出完整代码
4、遍历数据库查出来的字典数据,加入枚举中
5、输出并验证
6、packagecom.ly.ed挢旗扦渌;importjava.lang.reflect.AccessibleObject;足毂忍珩importjava.lang.reflect.Array;importjava.lang.reflect.Field;importjava.lang.reflect.Modifier;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importsun.reflect.ConstructorAccessor;importsun.reflect.FieldAccessor;importsun.reflect.ReflectionFactory;publicclassEnumService{publicstaticvoidmain(String[]args){//数据库查询// List<Map<String,Object>>dataList=daoc.queryData(...);List<Map<String,Object>>dataList=newArrayList<Map<String,Object>>();dataList.add(newHashMap<String,Object>());dataList.add(newHashMap<String,Object>());dataList.add(newHashMap<String,Object>());dataList.add(newHashMap<String,Object>());dataList.get(0).put("KEY","MON");dataList.get(0).put("VALUE",1);dataList.get(1).put("KEY","TUE");dataList.get(1).put("VALUE",2);dataList.get(2).put("KEY","WED");dataList.get(2).put("VALUE",3);dataList.get(3).put("KEY","THU");dataList.get(3).put("VALUE",4);//添加枚举for(Map<String,Object>map:dataList){addEnum(EnumDemo.class,map.get("KEY").toString(),map.get("VALUE"));}//打印验证for(EnumDemoe:EnumDemo.values()){System.out.println(e.toString());}}@SuppressWarnings("unchecked")publicstatic<TextendsEnum<?>>voidaddEnum(Class<T>enumType,Stringname,Objectvalue){//0.Sanitychecksif(!Enum.class.isAssignableFrom(enumType)){thrownewRuntimeException("class"+enumType+"isnotaninstanceofEnum");}FieldvaluesField=null;Field[]fields=EnumDemo.class.getDeclaredFields();for(Fieldfield:fields){if(field.getName().contains("$VALUES")){valuesField=field;break;}}AccessibleObject.setAccessible(newField[]{valuesField},true);try{//2.CopyitT[]previousValues=(T[])valuesField.get(enumType);List<T>values=newArrayList<T>(Arrays.asList(previousValues));//3.buildnewenumTnewValue=(T)makeEnum(enumType,name,values.size(),newClass[]{Integer.class},newObject[]{value});//4.addnewvaluevalues.add(newValue);Objectobject=values.toArray((EnumDemo[])Array.newInstance(EnumDemo.class,0));//5.SetnewvaluesfieldsetFailsafeFieldValue(valuesField,null,object);//6.CleanenumcachecleanEnumCache(EnumDemo.class);}catch(Exceptione){e.printStackTrace();thrownewRuntimeException(e.getMessage(),e);}}privatestaticvoidcleanEnumCache(Class<?>enumClass)throwsNoSuchFieldException,IllegalAccessException{blankField(enumClass,"enumConstantDirectory");//Sun(Oracle?!?)JDK1.5/6blankField(enumClass,"enumConstants");//IBMJDK}privatestaticvoidblankField(Class<?>enumClass,StringfieldName)throwsNoSuchFieldException,IllegalAccessException{for(Fieldfield:Class.class.getDeclaredFields()){if(field.getName().contains(fieldName)){AccessibleObject.setAccessible(newField[]{field},true);setFailsafeFieldValue(field,enumClass,null);break;}}}privatestaticvoidsetFailsafeFieldValue(Fieldfield,Objecttarget,Objectvalue)throwsNoSuchFieldException,IllegalAccessException{//let'smakethefieldaccessiblefield.setAccessible(true);//nextwechangethemodifierintheFieldinstanceto//notbefinalanymore,thustrickingreflectioninto//lettingusmodifythestaticfinalfieldFieldmodifiersField=Field.class.getDeclaredField("modifiers");modifiersField.setAccessible(true);intmodifiers=modifiersField.getInt(field);//blankoutthefinalbitinthemodifiersintmodifiers&=~Modifier.FINAL;modifiersField.setInt(field,modifiers);FieldAccessorfa=ReflectionFactory.getReflectionFactory().newFieldAccessor(field,false);fa.set(target,value);}privatestaticObjectmakeEnum(Class<?>enumClass,Stringvalue,intordinal,Class<?>[]additionalTypes,Object[]additionalValues)throwsException{Object[]parms=newObject[additionalValues.length+2];parms[0]=value;parms[1]=Integer.valueOf(ordinal);System.arraycopy(additionalValues,0,parms,2,additionalValues.length);returnenumClass.cast(getConstructorAccessor(enumClass,additionalTypes).newInstance(parms));}privatestaticConstructorAccessorgetConstructorAccessor(Class<?>enumClass,Class<?>[]additionalParameterTypes)throwsNoSuchMethodException{Class<?>[]parameterTypes=newClass[additionalParameterTypes.length+2];parameterTypes[0]=String.class;parameterTypes[1]=int.class;System.arraycopy(additionalParameterTypes,0,parameterTypes,2,additionalParameterTypes.length);returnReflectionFactory.getReflectionFactory().newConstructorAccessor(enumClass.getDeclaredConstructor(parameterTypes));}}