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.
Asked
Active
Viewed 6.0k times
7
-
Can you post your actual code ? – Max Mar 30 '15 at 13:38
-
i don't really have any code to show. I am sending a json to my rest controller. the json is bound the my object and then the object is passed through validation. i want an if statement in my validation to check that the data for 'accountType' is not empty. accountType is an Enum. Sorry for the bad explanation – Shaun Mar 31 '15 at 14:28
2 Answers
13
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.
On request here basics about Enum compare:
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"

Desislav Kamenov
- 1,193
- 6
- 13

Rene M.
- 2,660
- 15
- 24
-
okay so can you give me a code example on how to check on null and on equals in java please. – Shaun Mar 31 '15 at 14:40
-
ah okay i see this makes more sense, i sorted my problem. Thanks rmertins – Shaun Mar 31 '15 at 15:27
-
6
You can simply use : Objects.isNull(enumValue)

Aayush
- 409
- 4
- 17
-
1
-
or just simply `enumValue != null` since Objects.isNull only checks null reference – Paweł Sosnowski Nov 03 '22 at 10:51