I'm trying to build a dynamic wrapper that uses reflection to access properties of objects. My approach works with different kinds of objects – but I still have an issue with Enums.
Let's assume I already have the proper setter und getter and I want to invoke them in different situations. For example I'm trying to save a given value via 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 can I convert the String object to the proper Enum value?
I know about MyEnum.valueOf(String)... but what if I can't name the Enum in my source code? I've not managed to use something like
this.value = Enum.valueOf(this.getter.getReturnType(), this.value);
.getDeclaredFields()from the class object...Enumwiththisas they are implicitly static.