如何在Java中在运行时添加枚举字段

时间:2017-05-21 01:58:07

标签: java enums

如何在Java中在运行时添加HIGH(1)MEDIUM(2)LOW(3)等枚举字段?

public enum Status {
    HIGH,
    MEDIUM,
    LOW;  
}

1 个答案:

答案 0 :(得分:0)

最好的办法是使用反射。

有关示例,请参见此处:

http://www.jroller.com/VelkaVrana/entry/modify_enum_with_reflection

做这项工作的勇气就是这种方法:

/** 
 * <b>Experimental and too much related to internal java implementation - use on your own risk</b> 
 */  
public static void setStaticFieldValue(final Class beanClass, final String fieldName,  
                                       final Object newValue) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {  
    // TODO: find some better way how to change static field  
    Field field = getField(beanClass, fieldName);  
    boolean accessible = field.isAccessible();  

    field.setAccessible(true);  
    try {  
        FieldAccessor fieldAccessor = (FieldAccessor) invokeMethod(field, "getFieldAccessor", new Class[]{  
                Object.class  
        }, new Object[]{  
                beanClass  
        });  

        Object isReadOnly = getFieldValue(fieldAccessor, "isReadOnly");  
        try {  
            setFieldValue(fieldAccessor, "isReadOnly", false);  

            //field.set(beanClass, newValue);  
            fieldAccessor.set(beanClass, newValue);  
        } finally {  
            setFieldValue(fieldAccessor, "isReadOnly", isReadOnly);  
        }  
    } finally {  
        field.setAccessible(accessible);  
    }  
}  

你真的不应该在运行时修改枚举。也许考虑使用Set代替?