How to convert from String to Enum dynamically?

I am trying to create a dynamic wrapper that uses reflection to access the properties of objects. My approach works with different objects, but I still have a problem with Enums.

Suppose I already have the correct setter und getter, and I want to call them in different situations. For example, I am trying to save a given value with the following code:

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);
    }
}

How to convert a String object to the corresponding Enum value?

I know about MyEnum.valueOf(String)... but what if I cannot name Enum in my source code? I was not able to use something like

this.value = Enum.valueOf(this.getter.getReturnType(), this.value);
+4
source share
2 answers

Enum , Enum, , , java.lang.Enum:

static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)

.

java.awt.Window.Type type = Enum.valueOf(java.awt.Window.Type.class, "NORMAL");

, Enum.valueOf IllegalArgumentException, .

Enum.valueOf , getter.getReturnType() Class<?>.

, :

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

:

if (this.value instanceof String && this.getter.getReturnType().isEnum())
     this.value = getEnumValue(getter.getReturnType(), (String)this.value));

, , Enum.getEnumConstants(), , Enum.valueOf .

+3

... ""... ?

if (this.value instanceof String && this.getter.getReturnType().isEnum()) {
    for (Object v : this.getter.getReturnType().getEnumConstants()) {
        if (v.toString().equals(this.value)) {
            this.value = v;
            break;
        }
    }
}
0
source

Source: https://habr.com/ru/post/1599044/


All Articles