scphantm scphantm - 1 year ago 108
Java Question

How do I reimplement valueof on enumeration

I need to re-implement the enum.valueof method of a few of my enumerations so they no longer throw exceptions, instead they simply return null if a value doesn't exist in the enumeration.

I'm trying the basic

public static <T extends Enum<T>> T valueOf(Class<T> enumType,
String name){

but it's not working, saying I need to override or implement a super type.

I can come up with a super class I guess, but I'm just not sure how to put this together. Any ideas?

Answer Source

You can't. You'll have to define another, different method. The valueOf method is automatically generated by the compiler.

public static MyEnum permissiveValueOf(String name) {
    for (MyEnum e : values()) {
        if (e.getName().equals(name)) {
            return e;
    return null;