非空枚举就像非空对象一样?
我有一些获取枚举值的代码:
StringUtils.isEmpty(getEnumMember().value());
支持代码如下所示:
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;
}
...
}
我想知道是否有一种方法可以让 getEnumMember 以与处理空对象相同的方式处理空枚举。例如:
public CustomEnum getEnumMember() {
if (enumMember ==null) {
return new CustomEnum();
}
return enumMember;
}
但我无法实例化“new CustomEnum”。您将如何处理这个问题以使 getEnumMember() 不会返回 null?我不想为“ENUM_IS_NULL("")”创建特殊的枚举值。
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;
}
...
}
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("")".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您创建枚举时,您是说该类型的任何变量都将具有已定义的值列表之一 - 或者为 null。这是不可避免的。因此,您必须要么接受 null,要么确定一个适当的值 - 无论它是现有的枚举值之一还是您添加的新值。这些是你唯一的选择。代码
return new CustomEnum();
只是没有意义;您必须选择枚举值之一,并且必须指定是哪一个。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.做不到。枚举的部分思想是枚举所有可能的值,并且您不能只是添加更多值。
您必须执行以下操作:
或:
或在
StringUtils.isEmpty
中处理NullPointerException
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:
or:
or handle
NullPointerException
s inStringUtils.isEmpty