Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reimplement valueof on enumeration

Tags:

java

enums

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

@Override
    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?

like image 679
scphantm Avatar asked Oct 05 '11 13:10

scphantm


People also ask

Can we override enum valueOf?

By default, the enum value is its method name. You can however override it, for example if you want to store enums as integers in a database, instead of using their method name.

Can I override valueOf enum Java?

Since you cannot override valueOf method you have to define a custom method ( getEnum in the sample code below) which returns the value that you need and change your client to use this method instead. getEnum could be shortened if you do the following: v. getValue().

How do you find the value of an enum?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

What does valueOf do in enum?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)


1 Answers

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.name().equals(name)) {
            return e;
        }
    }
    return null;
}
like image 193
JB Nizet Avatar answered Oct 12 '22 01:10

JB Nizet