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?
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.
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().
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.
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.)
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;
}
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