Java 检查 Enum 是否为 null 或为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29347672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking to see if a an Enum is null or empty
提问by Shaun
I am trying to validate a json that is being sent into my controller and I am using the BindingResult way and I am able to validate strings and everything else fine as normal. But im not sure how to check if an Enum is empty or null.
我正在尝试验证正在发送到我的控制器的 json,并且我正在使用 BindingResult 方式,我能够像往常一样验证字符串和其他一切。但我不确定如何检查 Enum 是空的还是空的。
采纳答案by Rene M.
First of all an Enum can't be empty! It is an Object representing a defined state. Think of it like an static final Object which can't be changed after intialization, but easyly compared.
首先,枚举不能为空!它是一个代表定义状态的对象。把它想象成一个静态的最终对象,初始化后不能改变,但很容易比较。
So what you can do is check on null and on Equals to your existing Enum Values.
所以你可以做的是检查 null 和 Equals to your existing Enum Values。
On request here basics about Enum compare:
在此处请求有关 Enum 比较的基础知识:
public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Currency coin = Currency.PENNY;
Currency noCoin = null
Currency pennyCoin = Currency.PENNY;
Currency otherCoin = Currency.NICKLE;
if (coin != null) {
System.out.println("The coin is not null");
}
if (noCoin == null) {
System.out.println("noCoin is null");
}
if (coin.equals(pennyCoin)) {
System.out.println("The coin is a penny, because its equals pennyCoin");
}
if (coin.equals(Currency.PENNY)) {
System.out.println("The coin is a penny, because its equals Currency.PENNY");
}
if (!coin.equals(otherCoin)) {
System.out.println("The coin is not an otherCoin");
}
switch (coin) {
case PENNY:
System.out.println("It's a penny");
break;
case NICKLE:
System.out.println("It's a nickle");
break;
case DIME:
System.out.println("It's a dime");
break;
case QUARTER:
System.out.println("It's a quarter");
break;
}
Output: "It's a penny"
回答by Aayush
You can simply use : Objects.isNull(enumValue)
您可以简单地使用: Objects.isNull(enumValue)