将枚举字段设置为默认值,以防万一未传递值

发布于 2025-01-22 11:52:32 字数 519 浏览 2 评论 0原文

我有这样的性别枚举:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痴情 2025-01-29 11:52:32

方法 valueof(string)返回概述当参数无效时:

  • illegalargumentException如果指定的枚举类型没有指定名称的常数,或者指定的类对象没有代表对象。枚举类型
  • nullpoInterException如果enumtype或name为null,则

可以写:

public static GenderEnum from(String text) {
    GenderEnum gender;

    try {
        gender = valueOf(text);
    } catch (IllegalArgumentException | NullPointerException e) {
        gender = INVALID;
    }
    
    return gender;
}

或简化:

public static GenderEnum from(String text) {
    GenderEnum gender = INVALID;

    try {
        gender = valueOf(text);
    } catch (Exception ignore) { }
    
    return gender;
}

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 type
  • NullPointerException if enumType or name is null

You can write:

public static GenderEnum from(String text) {
    GenderEnum gender;

    try {
        gender = valueOf(text);
    } catch (IllegalArgumentException | NullPointerException e) {
        gender = INVALID;
    }
    
    return gender;
}

Or simplify:

public static GenderEnum from(String text) {
    GenderEnum gender = INVALID;

    try {
        gender = valueOf(text);
    } catch (Exception ignore) { }
    
    return gender;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文