2

I have the following class:

public class EnumContainer{

    private Class<?> enumClass;
    //GET, SET

    public EnumContainer(Class<?> clazz){
        this.enumClass = clazz;
    }

    public boolean tryCast(String value){
        //Here I should try to cast the String to the Enum by enumClass field

        //return true if cast was successfull
        //false otherwise
    }
}

Is it even possible in Java to perform such casting?

user3663882
  • 6,957
  • 10
  • 51
  • 92

1 Answers1

3

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 e.g. 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.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • Well, unchecked casting is always not a very good idea... And sincee I don't know how exactly it works internally I would prefer to not using your last aaproach. – user3663882 Apr 22 '15 at 08:48
  • @user3663882 Then don't. I'm one of the people who grumbles so it's fine with me if you don't. ; ) – Radiodef Apr 22 '15 at 08:48