How to cast a String value to an Enum value by Class?

This question already has an answer here:

  • Lookup Java enum by string value 23 answers

  • It's actually kind of a pain because of the way Enum is declared. You wouldn't be able to call valueOf with a Class<?> (nor eg a Class<? extends Enum<?>> ). The only way to do it without unchecked casting is to go through getEnumConstants :

    public boolean tryCast(String value){
        for(Object o : enumClass.getEnumConstants()) {
            Enum<?> e = (Enum<?>) o;
            if(e.name().equals(value))
                return true;
        }
        return false;
    }
    

    If you don't care about the unchecked cast you can do:

    try {
        Enum.valueOf( (Class) enumClass, value );
        return true;
    } catch(IllegalArgumentException e) {
        return false;
    }
    

    But, you know, some people will grumble because it's a raw type. getEnumConstants is probably better anyways since then you don't use exceptions for this kind of thing.


    In addition, since you have a Class<?> you might want to perform a check like

    if( !Enum.class.isAssignableFrom(enumClass) )
        return false;
    

    or throw an exception in the constructor.

    链接地址: http://www.djcxy.com/p/38108.html

    上一篇: 任何人都知道一个快速的方法来获得一个枚举值的自定义属性?

    下一篇: 如何通过类将字符串值转换为Enum值?