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?

15
  • 5
    Yes; it's .valueOf(). Commented Apr 22, 2015 at 8:27
  • @VinceEmigh Because I'm using hibernate and in order to simplify some mappings I need to use @Type annotation which reffers to the type that have to containt the Class<?> field. From the web page I can only grab a String value. Commented Apr 22, 2015 at 8:30
  • @fge Couldn't you provide a complete answer? Commented Apr 22, 2015 at 8:35
  • @fge What object should I perform method.invoke(obj, args) call on? Commented Apr 22, 2015 at 8:39
  • 1
    This isn't casting. Stop saying casting. Commented Apr 22, 2015 at 8:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 Then don't. I'm one of the people who grumbles so it's fine with me if you don't. ; )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.