如何从字符串动态转换为枚举?

Dan*_*ner 5 java enums

我正在尝试构建一个使用反射来访问对象属性的动态包装器。我的方法适用于不同类型的对象——但我仍然对 Enums 有问题。

让我们假设我已经有了合适的 setter 和 getter,我想在不同的情况下调用它们。例如,我试图通过以下代码保存给定值:

public void save() {
    try {
        // Enums come in as Strings... we need to convert them!
        if (this.value instanceof String && this.getter.getReturnType().isEnum()) {

            // FIXME: HOW?

        }
        this.setter.invoke(this.entity, this.value);
    }
    catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
        throw new RuntimeException("Die Eigenschaft " + this.property + " von Entity " + this.entity.getClass().getSimpleName() + " konnte nicht geschrieben werden!", ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何将 String 对象转换为正确的 Enum 值?

我知道MyEnum.valueOf(String)......但是如果我不能在我的源代码中命名 Enum 怎么办?我还没有设法使用类似的东西

this.value = Enum.valueOf(this.getter.getReturnType(), this.value);
Run Code Online (Sandbox Code Playgroud)

wer*_*ero 4

给定一个 Enum 类和一个字符串值,您可以通过以下定义的静态方法转换为与该字符串对应的 Enum 对象java.lang.Enum

static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
Run Code Online (Sandbox Code Playgroud)

例如

java.awt.Window.Type type = Enum.valueOf(java.awt.Window.Type.class, "NORMAL");
Run Code Online (Sandbox Code Playgroud)

请注意,如果没有相应的枚举常量,Enum.valueOf则会抛出异常。IllegalArgumentException

Enum.valueOf如果没有方法的强制转换,您就无法调用,因为getter.getReturnType()is a Class<?>

因此,辅助函数可能会处理转换:

@SuppressWarnings("unchecked")
private static <E extends Enum<E>> E getEnumValue(Class<?> c, String value)
{
     return Enum.valueOf((Class<E>)c, value);
}
Run Code Online (Sandbox Code Playgroud)

你只需在代码中使用它:

if (this.value instanceof String && this.getter.getReturnType().isEnum())
     this.value = getEnumValue(getter.getReturnType(), (String)this.value));
Run Code Online (Sandbox Code Playgroud)

请注意,任何循环的解决方案Enum.getEnumConstants()都会为常量创建一个临时数组,而Enum.valueOf使用内部缓存。