I have an Enum like this:
public enum Type{
CSV, EXCEL, PDF, URL, NULL
}
now I read a String from an xml-file and use Type.valueOf(string);
to parse the value to the enum. if this part does not exist in the xml-file, the string is null
and not "null"
. Is there a way to convert null
to "null"
or should change the return null;
to return "null";
? or should null not even be a part of the enum?
Enum types cannot be nullable.
If the parsed value is not equivalent to one of the Enum values, you could return a null and then check for null every where in the code before using this Enum.
Yes, the only downside there is that the value for null would have to be the default value for value types — otherwise, values that are not explicitly initialized would have strange, non-default values rather than null.
Enums can't be nullable.
What you should do is use something else than NULL
and parse that case differently:
public enum Type {
CSV, EXCEL, PDF, URL, NONE;
public static Type from(String text) {
if (text == null) {
return NONE;
} else {
return valueOf(text.toUpperCase());
}
}
}
Or better yet, use optionals:
public enum Type {
CSV, EXCEL, PDF, URL; // Note the absence of NULL/NONE/WHATEVER
public static Optional<Type> from(String text) {
return Optional.ofNullable(text)
.map(String::toUpperCase)
.map(Type::valueOf);
}
}
If you call Type.valueOf(null)
you'll get a NullPointerException
. So I would suggest two solutions:
write a utility function which includes a null
check:
public static Type getType(String name) {
if (name == null)
return Type.NULL;
else
return Type.valueOf(name.toUpperCase());
}
create a map from the name to the field (except for NULL
) and add a getter to your enum:
public enum Type {
CSV, EXCEL, PDF, URL, NULL;
private static final Map<String, Type> TYPE_BY_NAME = new HashMap<>();
static {
TYPE_BY_NAME.put(CSV.name(), CSV);
TYPE_BY_NAME.put(EXCEL.name(), EXCEL);
TYPE_BY_NAME.put(PDF.name(), PDF);
TYPE_BY_NAME.put(URL.name(), URL);
TYPE_BY_NAME.put(null, NULL);
}
public static Type getType(String name) {
String s = name == null ? null : name.toUpperCase();
return TYPE_BY_NAME.get(s);
}
The second solution needs a bit more typing but you don't get an exception if the name does not exist. If you're sure that only the fields of your enum are given I would prefer the first solution.
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