问题
I'm having a bit of a problem with some legacy code. A ticket asks for me to write a script testing the validity of a process; however, I keep getting this exception when the script is run:
java.lang.IllegalArgumentException: No enum const class edu.cmu.s3.common.enums.RegistrationStatus.;
For the record, the database being used is an old Ingres legacy system, so null values are being represented as empty strings -- quite beautiful, I have to add.
Anyway, it looks like whenever an empty string is encountered, it fails on enum creation. I checked the enum, though, and it contains this member:
BLANK("", "Blank")
This would make me think that an empty string is indeed a valid argument, but it looks like it's not.
CAN enums use empty strings as arguments, or will I need to update more legacy code than I initially assumed?
Thanks for the help
回答1:
An empty string is a valid argument for an enum constructor - but it's not a valid enum name.
Every enum value name has to be a valid Java identifier.
回答2:
If you're using Enum.valueOf(String)
to parse Strings
from your database into Enums
, then your problem is that valueOf
keys off of the Enum
name itself, i.e. BLANK
.
This would work for you: Enum.valueOf( "BLANK" )
But not: Enum.valueOf( "" )
If you wanted to parse Enums
based on some other field pased into the Enum
constructor, you would have to write that code yourself.
来源:https://stackoverflow.com/questions/10179785/are-empty-strings-allowed-as-enum-members-in-java