动态生成enum(dynamic enum)

因为以前的老代码定义了enum类,而这部分代码是作为公共的jar,修改时会影响很大,所以希望动态添加枚举属性

首先是一个工具类DynamicEnumUtil ,参考网上的:

原文链接:

http://bbs.csdn.net/topics/391037532

https://www.niceideas.ch/roller2/badtrash/entry/java_create_enum_instances_dynamically



import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.**.enums.Carrier;

import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;
import sun.reflect.ReflectionFactory;

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  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 > void addEnum(Class 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 values = new ArrayList(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) {
           e.printStackTrace();
           throw new RuntimeException(e.getMessage(), e);
       }
   }


   public static void main(String[] args) {
	   
	   System.out.println(Arrays.deepToString(Carrier.values()));
       // Dynamically add 1 instance
       addEnum(Carrier.class,"test60",new Class[]{int.class,String.class, String.class}, new Object[]{60, "test60","CHINA"});
       addEnum(Carrier.class,"test60",new Class[]{int.class,String.class, String.class}, new Object[]{60, "test60","CHINA"});
       // Run a few tests just to show it works OK.
       System.out.println(Arrays.deepToString(Carrier.values()));
       Carrier[] carriers = Carrier.values();
       System.out.println(carriers[1].getId());
   }
   

}


枚举类Carrier里包含三个属性:

public enum Carrier implements Serializable{
	 
    UNKNOWN(0,"",""),
    AIRCEL(1,"Aircel","IN"),
  .....
    private int id;
    private String name;
    private String country;
....
}

然后定义了一个schedule每5分钟去数据库查找是否有新的carrier信息,如果有添加新的enum属性

public class CarrierLoader {

	private static final int RELOAD_PERIOD = 5 * 60 * 1000;//5 mins
    private static int i=0;
	static {
		//checkNewCarrier();
		new Timer(true).schedule(new TimerTask() {
			public void run() {
				try {
					System.out.println("runner ---------------");
					checkNewCarrier();
					if(i<60) i++;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, RELOAD_PERIOD, RELOAD_PERIOD);
	}

    public static void checkNewCarrier(){
    	Map carriers = DBUtil.loadCarrier();//query carriers from DB
		List newCarriers = new ArrayList();
		for(int id:carriers.keySet())
		{                          
			if(!Carrier.getCarrierMap().keySet().contains(id)){//add new carrier to newCarriers
				newCarriers.add(carriers.get(id));
			}
		}
		if(newCarriers!=null && newCarriers.size()>0){
			for(CarrierBean carrier:newCarriers){
				System.out.println("add new carrier:"+carrier.getId());
				DynamicEnumUtil.addEnum(Carrier.class, carrier.getName(), new Class[]{int.class,String.class, String.class}, new Object[]{carrier.getId(), carrier.getName(),carrier.getCountry()});
			}
			Carrier.initCarrierMap();//reset the carrierMap
		}else{
			System.out.println("no new carrier");
			System.out.println("get carrier fromid="+i+"------"+Carrier.fromInt(i));
		}
		
    }

	public static void main(String[] args) {
		System.out.println("get carrier fromid=4###ID="+Carrier.fromInt(4).getId()+"##NAME="+Carrier.fromInt(4).getName()+"##COUNTRY="+Carrier.fromInt(4).getCountry());
	}

}















本文参考:

http://bbs.csdn.net/topics/391037532

https://www.niceideas.ch/roller2/badtrash/entry/java_create_enum_instances_dynamically

你可能感兴趣的:(java基础)