Search code examples
javahibernateclassenumshibernate-criteria

When class is detected as it extends Enum, how to call its valueOf() method?


I have an Enum in Java:

public enum TypeOfUser {
    EMPLOYEE("EMPLOYEE"),
    EMPLOYER("EMPLOYER");

    private final String type;
    TypeOfUser(final String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }
}

And I use it in Hibernate mapping, so if I want to add filtering I use Criteria interface. I build criteria based on Map, at this moment I detect whether it inherits from Enum (cause every Enum implicitly inherits from Java Enum class) and call valueOf() method of TypeOfUser:

Class fieldClass = element.getValue().getValue();
if (Enum.class.isAssignableFrom(fieldClass)) {
     criteria.add(
         Restrictions.eq(element.getKey(), 
         TypeOfUser.valueOf(element.getValue().getKey()))
      );
}

But it works only because I have only one Enum im my project, and in future there will be more of them, like Months or so. Is there a way, when class is detected as Enum, to cast it and then call its valueOf() method? Something like:

Class fieldClass = element.getValue().getValue();
if (Enum.class.isAssignableFrom(fieldClass)) {
     criteria.add(
         Restrictions.eq(element.getKey(),
         ((Enum.class)fieldClass).valueOf(element.getValue().getKey()))
      );
 }

I want to do it to avoid if-else or switch instruction, like:

if (fieldClass.equals(TypeOfUser.class)) {
    value = TypeOfUser.valueOf(key);
}
else if (fieldClass.equals(Months.class)) {
    value = Months.valueOf(key);
}

Because they can be really tricky to maintain when many Enums will exist in project. Is there a chance to do it in Java? Thank you in advance for any help.


Solution

  • You are looking for Enum.valueOf

    Class<E> enumClass = ...
    String name = ...
    E e = Enum.valueOf(enumClass, name);