我有一个枚举:
public enum Language {
EN_GB("en-gb"),
EN_DE("en-de"),
DE_DE("de-de");
private final String text;
Language(final String text) {
this.text = text;
}
@JsonValue
public String getValue() {
return text;
}
}
我有一个用于枚举转换的类:
public class EnumConverter {
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");
}
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 <T> 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 <T extends Enum<?>> void addEnum( Class<T> 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<T> values = new ArrayList<T>(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<?>[] {}, // could be used to pass values to the enum constuctor if needed
new Object[] {}); // could be used to pass values to the enum constuctor if needed
// 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);
}
}
}
我得到例外
java.lang.NoSuchMethodException: com.staxter.models.response.auth.Language.<init>(java.lang.String, int)
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at com.staxter.utility.EnumConverter.getConstructorAccessor(EnumConverter.java:61)
at com.staxter.utility.EnumConverter.makeEnum(EnumConverter.java:70)
at com.staxter.utility.EnumConverter.addEnum(EnumConverter.java:105)
java.lang.RuntimeException: com.staxter.models.response.auth.Language.<init>(java.lang.String, int) at com.staxter.utility.EnumConverter.addEnum(EnumConverter.java:122)
所以我的问题是:
为什么会出现这种异常以及我应该在enumConverter类中进行哪些编辑?
P.S。如果我从枚举中删除所有字符串参数和方法,则没有异常,并且测试成功。但是我需要字符串参数。
答案 0 :(得分:0)
如果我正确理解了您的问题。您想从String实例获取枚举类型。
要解决此问题,您不需要单独的类。
您可以使用静态方法:
public enum Language {
EN_GB("en-gb"),
EN_DE("en-de"),
DE_DE("de-de");
private final String text;
Language(final String text) {
this.text = text;
}
@JsonValue
public String getValue() {
return text;
}
public static Language fromString(String str) {
for (Language lang : Language.values()) {
if (lang.getValue().equalsIgnoreCase(str)) {
return lang;
}
}
throw new IllegalArgumentException("Illegal enum parameter: " + str);
}
public static void main(String[] args) {
System.out.println(Language.fromString("en-de"));
System.out.println(Language.fromString("en-gb"));
System.out.println(Language.fromString("en-dd"));
}
}
输出:
EN_DE
EN_GB
Exception in thread "main" java.lang.IllegalArgumentException: Illegal enum parameter: en-dd
at com.tribe.pdf2data.pdf2data.dto.Language.fromString(Language.java:27)
at com.tribe.pdf2data.pdf2data.dto.Language.main(Language.java:33)
答案 1 :(得分:0)
将工厂方法添加到您的枚举。 Jackson 将调用此方法以反序列化您的枚举。
public enum Language {
// ...
@JsonCreator
public static Language parseId(String text) {
for (Lanugage language : values())
if (language.text.equalsIgnoreCase(text))
return language;
throw new EnumConstantNotPresentException(Language.class, text);
}
}
或者,您可以为此枚举声明自定义反序列化器。
答案 2 :(得分:0)
更新 我选择使用Locale类。这对我来说更合适,并且我的项目也不会困难。谢谢您的提示,伙计们!