Non-Null Enums like non-null Objects?
I have some code that acquires a value for an enum:
StringUtils.isEmpty(getEnumMember().value());
The supporting code looks like this:
public CustomEnum getEnumMember() {
return enumMember;
}
----
public enum CustomEnum {
TEXT1("text1"),
TEXT2("text2"),
TEXT3("text3");
private final String value;
CustomEnum(String v) {
value = v;
}
public String value() {
return value;
}
...
}
开发者_StackOverflow中文版I am wondering if there is a way for getEnumMember to handle null enums in the same way I can handle null objects. For example:
public CustomEnum getEnumMember() {
if (enumMember ==null) {
return new CustomEnum();
}
return enumMember;
}
But I cannot instantiate a "new CustomEnum". How would you handle this so that getEnumMember() would not return a null? I would prefer not to create a special enum value for "ENUM_IS_NULL("")".
When you create an enum, you're saying that any variable of that type will have one of a defined list of values - or be null. That's inescapable. So you must either accept the null, or determine an appropriate value - whether it is one of your existing enum values or a new one you add. These are your only options. The code return new CustomEnum();
just doesn't make sense; you must be selecting one of the enumerated values, and you have to specify which one.
Can't be done. Part of the idea of an enum is that all possible values are enumerated and you can't just add more.
You'll either have to do:
public enum CustomEnum {
TEXT1("text1"),
TEXT2("text2"),
TEXT3("text3"),
ENUM_IS_NULL("");
...
}
or:
StringUtils.isEmpty(getEnumMember() == null? "" : getEnumMember().value());
or handle NullPointerException
s in StringUtils.isEmpty
精彩评论