我正在尝试验证要发送到控制器中的json,并且正在使用BindingResult方式,并且能够验证字符串以及其他一切正常。但是我不确定如何检查枚举是否为空或空。

最佳答案

首先,枚举不能为空!它是一个代表已定义状态的对象。可以将其视为静态的最终对象,该对象在初始化后就无法更改,但可以轻松进行比较。

因此,您可以做的是检查null是否等于现有的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"

09-25 21:02