覆盖 Java 枚举中的 valueof() 和 toString() [英] Override valueof() and toString() in Java enum

查看:28
本文介绍了覆盖 Java 枚举中的 valueof() 和 toString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 enum 中的值是需要在其中包含空格的单词,但是枚举的值中不能包含空格,因此它们都被捆绑在一起.我想覆盖 toString() 以在我告诉它的地方添加这些空格.

The values in my enum are words that need to have spaces in them, but enums can't have spaces in their values so it's all bunched up. I want to override toString() to add these spaces where I tell it to.

当我在添加空格的同一个字符串上使用 valueOf() 时,我还希望枚举提供正确的枚举.

I also want the enum to provide the correct enum when I use valueOf() on the same string that I added the spaces to.

例如:

public enum RandomEnum
{
     StartHere,
     StopHere
}

在值为 StartHereRandomEnum 上调用 toString() 返回字符串 "Start Here".在同一个字符串上调用 valueof() ("Start Here") 返回枚举值 StartHere.

Call toString() on RandomEnum whose value is StartHere returns string "Start Here". Call valueof() on that same string ("Start Here") returns enum value StartHere.

我该怎么做?

推荐答案

你可以试试这个代码.由于您无法覆盖 valueOf 方法,因此您必须定义一个自定义方法(以下示例代码中的 getEnum),该方法返回您需要的值并更改您的客户端以使用此方法相反.

You can try out this code. Since you cannot override valueOf method you have to define a custom method (getEnum in the sample code below) which returns the value that you need and change your client to use this method instead.

public enum RandomEnum {

    StartHere("Start Here"),
    StopHere("Stop Here");

    private String value;

    RandomEnum(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return this.getValue();
    }

    public static RandomEnum getEnum(String value) {
        for(RandomEnum v : values())
            if(v.getValue().equalsIgnoreCase(value)) return v;
        throw new IllegalArgumentException();
    }
}

这篇关于覆盖 Java 枚举中的 valueof() 和 toString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆