动态枚举 - 枚举在程序运行过程中动态添加

业务背景:在复杂业务场景下,原定义的枚举类型不满足现有需求,且枚举类型要添加的数量不确定。

工具类:DynamicEnumUtils   动态枚举操作工具

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 sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;
import sun.reflect.ReflectionFactory;

/**  
* @Description: 动态枚举操作工具
* @author ***
* @date 2019年11月29日
*/
@SuppressWarnings("restriction")
public class DynamicEnumUtils {
	private static ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory();

	private static void setFailsafeFieldValue(Field field, Object target, Object value) throws NoSuchFieldException,
	           IllegalAccessException {

	    field.setAccessible(true);
	
	    Field modifiersField = Field.class.getDeclaredField("modifiers");
	    modifiersField.setAccessible(true);
	    int modifiers = modifiersField.getInt(field);
	
        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));
    }

    @SuppressWarnings("unchecked")
    public static > void addEnum(Class enumType, String enumName, Class[] additionalTypes, Object[] additionalValues) {

        // 判断该枚举类是否继承自枚举Enum
        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) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    
}

 

应用:在程序业务流程中动态添加一个枚举到原有枚举类中

DynamicEnumUtils.addEnum(***Enum.class, enumName
			, new Class[]{java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class}
			, new Object[]{value1, value2, value3}
		);

 

你可能感兴趣的:(javaACM,Java,锁,java,exception,体系)