简体   繁体   English

是否允许空字符串作为Java中的枚举成员

[英]Are empty strings allowed as enum members in Java

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. 作为记录,使用的数据库是一个旧的Ingres旧系统,因此空值表示为空字符串-非常漂亮,我必须添加。

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? CAN枚举可以使用空字符串作为参数,还是我需要更新比最初设想的更多的旧代码?

Thanks for the help 谢谢您的帮助

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. 每个枚举值名称都必须是有效的Java标识符。

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, ie BLANK . 如果您使用Enum.valueOf(String)将数据库中的Strings解析为Enums ,那么您的问题是valueOf键脱离了Enum名称本身,即BLANK

This would work for you: Enum.valueOf( "BLANK" ) 这将为您工作: Enum.valueOf( "BLANK" )

But not: Enum.valueOf( "" ) 但不是: 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. 如果你想解析Enums基于pased到其他一些领域Enum的构造函数,你就必须自己编写的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM