如何动态创建枚举?

我需要根据数据库中的表创建一个枚举。

数据库表MyColors:id / title / value 1 / Red / 1 2 / Green / 4

动态创造

enum MyColors { Red=1, Green=4; } 

您可以通过从数据库中读取动态创建源代码,并以有助于构建枚举的格式输出结果。 但是,在运行时创建枚举是不切实际的。 使用某种关联数组会更好。

实际上有可能使用reflection动态创建枚举: http : //niceideas.ch/roller2/badtrash/entry/java_create_enum_instances_dynamically

一个选项是将XML Schema和所需值定义为枚举并生成类文件,以便我们可以管理源代码之外的值,但是我们无法从数据库动态生成枚举值。

目前尚不清楚是否要生成源代码。 我猜不是,因为即使编译在同一程序中没有代码可以访问枚举对象,除非通过reflection。

那么为什么不使用JPA将表映射到ColorEntity对象呢? 然后,您可以拥有这些实体的列表或地图或您需要的任何内容。

 /** * 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) { // 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, // The target enum class enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED values.size(), new Class<><[] {}, // can be used to pass values to the enum constuctor new Object[] {}); // can be used to pass values to the enum constuctor // 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); } } 

以上代码可能对您有所帮助。