我正在尝试验证正在发送到我的控制器的json,并且我正在使用BindingResult方式,我能够正常验证字符串和其他所有内容。但我不知道如何检查枚举是空还是空。
答案 0 :(得分:6)
首先,Enum不会是空的!它是表示已定义状态的Object。可以把它想象成一个静态的最终对象,它在初始化后无法改变,但很容易进行比较。
所以你可以做的是检查null和Equals到你现有的枚举值。
根据要求,这里有关于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"
答案 1 :(得分:0)
您可以简单地使用:Objects.isNull(enumValue)