将枚举字段设置为默认值,以防万一未传递值
我有这样的性别枚举:
public enum GenderEnum {
INVALID,
MALE,
FEMALE;
public static GenderEnum from(String text) {
if (text == null) {
return INVALID;
} else {
return valueOf(text);
}
}
}
我有另一个类,它使用genderenum
的参考。在某些情况下,我们不会获得性别的任何价值,在这种情况下,呼叫失败的消息无法转换属性
。默认情况下,如何将其设置为无效?
例子
public class User {
//.... other fields ....
private GenderEnum gender;
}
I have a gender enum like this:
public enum GenderEnum {
INVALID,
MALE,
FEMALE;
public static GenderEnum from(String text) {
if (text == null) {
return INVALID;
} else {
return valueOf(text);
}
}
}
I have another class which uses a reference of GenderEnum
. There could be instances when we won't get any value for gender, in such cases, the call fails with message could not convert attribute
. How can I make it set to INVALID by default?
Example
public class User {
//.... other fields ....
private GenderEnum gender;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
方法 valueof(string)返回概述当参数无效时:
illegalargumentException
如果指定的枚举类型没有指定名称的常数,或者指定的类对象没有代表对象。枚举类型nullpoInterException
如果enumtype或name为null,则可以写:
或简化:
The method valueOf(String) return Expection when argument is invalid :
IllegalArgumentException
if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum typeNullPointerException
if enumType or name is nullYou can write:
Or simplify: