Are empty strings allowed as enum members in Java

旧时模样 提交于 2020-01-03 19:37:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!