检查枚举是否为 null 或为空

Checking to see if a an Enum is null or empty

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

首先Enum不能为空!它是一个表示已定义状态的对象。把它想象成一个静态的最终对象,它在初始化后不能改变,但很容易比较。

所以您可以做的是检查 null 和是否等于您现有的枚举值。

在此处请求枚举比较的基础知识:

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"

您可以简单地使用:Objects.isNull(enumValue)