简体   繁体   中英

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 Enum s will exist in project. Is there a chance to do it in Java ? Thank you in advance for any help.

You are looking for Enum.valueOf

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

我认为Enum.valueOf(fieldClass, key)应该可以工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM