Say I have an enum which is just
public enum Blah {
A, B, C, D
}
and I would like to find the enum value of a string, for example
As a switch
-version has not been mentioned yet I introduce it (reusing OP's enum):
private enum Blah {
A, B, C, D;
public static Blah byName(String name) {
switch (name) {
case "A":
return A;
case "B":
return B;
case "C":
return C;
case "D":
return D;
default:
throw new IllegalArgumentException(
"No enum constant " + Blah.class.getCanonicalName() + "." + name);
}
}
}
Since this don't give any additional value to the valueOf(String name)
method, it only makes sense to define an additional method if we want have a different behavior. If we don't want to raise an IllegalArgumentException
we can change the implementation to:
private enum Blah {
A, B, C, D;
public static Blah valueOfOrDefault(String name, Blah defaultValue) {
switch (name) {
case "A":
return A;
case "B":
return B;
case "C":
return C;
case "D":
return D;
default:
if (defaultValue == null) {
throw new NullPointerException();
}
return defaultValue;
}
}
}
By providing a default value we keep the contract of Enum.valueOf(String name)
without throwing an IllegalArgumentException
in that manner that in no case null
is returned. Therefore we throw a NullPointerException
if the name is null
and in case of default
if defaultValue
is null
. That's how valueOfOrDefault
works.
This approach adopts the design of the Map
-Interface which provides a method Map.getOrDefault(Object key, V defaultValue)
as of Java 8.