如何重新实现枚举的 valueof

发布于 2024-12-08 10:52:02 字数 312 浏览 2 评论 0原文

我需要重新实现一些枚举的 enum.valueof 方法,以便它们不再抛出异常,而是在枚举中不存在值时简单地返回 null。

我正在尝试基本功能

@Override
    public static <T extends Enum<T>> T valueOf(Class<T> enumType,
            String name){

,但它不起作用,说我需要覆盖或实现超级类型。

我想我可以想出一个超级类,但我只是不确定如何将它们组合在一起。有什么想法吗?

I need to re-implement the enum.valueof method of a few of my enumerations so they no longer throw exceptions, instead they simply return null if a value doesn't exist in the enumeration.

I'm trying the basic

@Override
    public static <T extends Enum<T>> T valueOf(Class<T> enumType,
            String name){

but it's not working, saying I need to override or implement a super type.

I can come up with a super class I guess, but I'm just not sure how to put this together. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(5

白芷 2024-12-15 10:52:02

你不能。您必须定义另一种不同的方法。 valueOf 方法由编译器自动生成。

public static MyEnum permissiveValueOf(String name) {
    for (MyEnum e : values()) {
        if (e.name().equals(name)) {
            return e;
        }
    }
    return null;
}

You can't. You'll have to define another, different method. The valueOf method is automatically generated by the compiler.

public static MyEnum permissiveValueOf(String name) {
    for (MyEnum e : values()) {
        if (e.name().equals(name)) {
            return e;
        }
    }
    return null;
}
烟若柳尘 2024-12-15 10:52:02

使用 Apache Commons Lang:

MyEnum myEnum = EnumUtils.getEnum(MyEnum.class, "MY_ENUM_VALUE");

引用 EnumUtils.getEnum 的 Javadoc

获取类的枚举,如果未找到则返回 null。

此方法与 Enum.valueOf(java.lang.Class,
java.lang.String),因为它不会抛出异常
无效的枚举名称。

Use Apache Commons Lang:

MyEnum myEnum = EnumUtils.getEnum(MyEnum.class, "MY_ENUM_VALUE");

Quote from the Javadoc for EnumUtils.getEnum:

Gets the enum for the class, returning null if not found.

This method differs from Enum.valueOf(java.lang.Class,
java.lang.String) in that it does not throw an exception for an
invalid enum name.

叫嚣ゝ 2024-12-15 10:52:02

该方法是否绝对有必要像枚举自动具有的方法一样调用 valueOf ?在我目前正在进行的项目中,我们有类似的方法,但我们对它们的称呼不同;例如,forName

public static ESomeEnum forName(String name) {
    for (ESomeEnum e : ESomeEnum.values()) {
        if (e.name().equals(name)) {
            return e;
        }
    }

    return null;
}

Is it absolutely necessary that the method is called valueOf like the method that enums have automatically? In the project that I'm currently working on we have similar methods, but we call them differently; for example, forName:

public static ESomeEnum forName(String name) {
    for (ESomeEnum e : ESomeEnum.values()) {
        if (e.name().equals(name)) {
            return e;
        }
    }

    return null;
}
浊酒尽余欢 2024-12-15 10:52:02

您不必覆盖 valueOf。这就是我所做的:

我必须将一些字符串“解析”为枚举,但它们与声明名称不匹配,因此我对 valueOf(String name) 进行了某种重新实现。

public enum Command {
    DIR("DIR"),
    PUT("PUT"),
    GET("GET"),
    OK("OK"),
    ERROR("ERROR"),
    READY("READY"),
    FIN("#FIN#");

    private String name;

    private Command(final String name) {
        this.name = name;
    }

    /**
     * Returns the desired Enum or throws an exception
     * @param commandName - String with the name contained by the Enum that you want
     * @return Command
     */
    public static Command getEnum(String commandName){
        // if the string is "#FIN#" returns Command.FIN.
        if(FIN.toString().equals(commandName)){
            return FIN;
        }
        // if the name matches any of the remaining enums return whichever one matches
        else if(Arrays.asList(Command.values()).contains(Command.valueOf(commandName))){
            return Command.valueOf(commandName);
        }
        // if it still wasn't found, throw an exception
        throw new IllegalArgumentException("No enum defined for this string: " + commandName);
    }

    @Override
    public String toString(){
            return name;
        }
    }

这段代码已经过测试并且可以工作。

您可以使用类似:

Command k = Command.getEnum("#FIN#");
System.out.println(k.name() + "  " +k.toString());
k = Command.getEnum("PUT");
System.out.println(k.name() + "  " +k.toString());

它的输出将是:

FIN  #FIN#
PUT  PUT

希望它有帮助。

You don't have to override valueOf. Here's what I did:

I had to "parse" some strings to enums and they didn't match with their declaration names, so I did a sort of reimplementation of valueOf(String name).

public enum Command {
    DIR("DIR"),
    PUT("PUT"),
    GET("GET"),
    OK("OK"),
    ERROR("ERROR"),
    READY("READY"),
    FIN("#FIN#");

    private String name;

    private Command(final String name) {
        this.name = name;
    }

    /**
     * Returns the desired Enum or throws an exception
     * @param commandName - String with the name contained by the Enum that you want
     * @return Command
     */
    public static Command getEnum(String commandName){
        // if the string is "#FIN#" returns Command.FIN.
        if(FIN.toString().equals(commandName)){
            return FIN;
        }
        // if the name matches any of the remaining enums return whichever one matches
        else if(Arrays.asList(Command.values()).contains(Command.valueOf(commandName))){
            return Command.valueOf(commandName);
        }
        // if it still wasn't found, throw an exception
        throw new IllegalArgumentException("No enum defined for this string: " + commandName);
    }

    @Override
    public String toString(){
            return name;
        }
    }

This code is tested and works.

You can use like:

Command k = Command.getEnum("#FIN#");
System.out.println(k.name() + "  " +k.toString());
k = Command.getEnum("PUT");
System.out.println(k.name() + "  " +k.toString());

And it's output would be:

FIN  #FIN#
PUT  PUT

Hope it helps.

秋风の叶未落 2024-12-15 10:52:02

您可以考虑在枚举类中创建一个新的(不同名称,例如转换)静态方法。

public enum MyEnum{
      ....

     public static MyEnum convert(Object value){
       ...
     }
}

You might consider creating a new (different name such as convert) static method in your enum classes.

public enum MyEnum{
      ....

     public static MyEnum convert(Object value){
       ...
     }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文