Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a valueOf generic enum?

Tags:

java

I'm trying to make an interface with a default method that returns valueOf(string) of that enum or null it there isn't any, so I can easily implement it without needing to paste the non-generic variant of this code in all classes in which I need such thing. So I tried doing this but it doesn't compile:

public interface EnumWNull<T extends Enum<T>> {
    default T getEnumOrNull(String value){
        try {
            return Enum.valueOf(T /*Error: expression expected*/, value);
        }catch (Exception e){
            return null;
        }
    }
}

I don't understand why. And I actually know I can just read all the values and search for it manually, however I want to know a better way than that for the sake of learning and elegance(and I feel like there should be a better way, if there isn't, what's the purpose of the static variant of valueOf ?).

like image 776
LightningShock Avatar asked Jan 28 '23 16:01

LightningShock


2 Answers

You can't do it without passing a Class object. You'll need to mimic the signature of Enum.valueOf():

static <T extends Enum<T>> T getEnumOrNull(Class<T> enumType, String name) {
    try {
        return Enum.valueOf(enumType, name);
    } catch (IllegalArgumentException e) {
        return null;
    }
}
like image 132
shmosel Avatar answered Jan 31 '23 18:01

shmosel


Instead of implementing an interface with a default method, I suggest creating a static utility method. @shmosel's answer nicely does this, but I suggest using Optional to convey that the method can return null (I've forked his code).

public static <T extends Enum<T>> Optional<T> getEnumValue(Class<T> enumType, String name) {
    try {
        return Optional.of(Enum.valueOf(enumType, name));
    } catch (IllegalArgumentException e) {
        return Optional.empty();
    }
}
like image 30
FThompson Avatar answered Jan 31 '23 19:01

FThompson