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 ?).
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;
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With