Java枚举 - 为什么使用toString而不是名字 [英] Java enum - why use toString instead of name

查看:235
本文介绍了Java枚举 - 为什么使用toString而不是名字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您使用方法 name()查看枚举api,则表示:

If you look in the enum api at the method name() it says that:


返回此枚举常量的名称,与其枚举声明中声明的完全相同。
大多数程序员应该优先使用toString方法,
作为toString方法可能会返回一个更加用户友好的名称。
此方法主要用于专门的情况,其中正确性取决于获取确切的名称,这从发布到发布不会有所不同。

Returns the name of this enum constant, exactly as declared in its enum declaration. Most programmers should use the toString method in preference to this one, as the toString method may return a more user-friendly name. This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.

为什么最好使用 toString()?我的意思是当name()已经是final时,toString可能会被覆盖。所以如果你使用toString和某人覆盖它来返回一个硬编码的价值,你的整个应用程序是关闭的...另外,如果你看到的源,toString()方法返回完全和只是名称。这是同样的事情。

Why is better to use toString()? I mean toString may be overridden when name() is already final. So if you use toString and someone overrides it to return a hard-coded value your whole application is down... Also if you look in the sources the toString() method returns exactly and just the name. It's the same thing.

推荐答案

这真的取决于你想对返回的值做什么:

It really depends on what you want to do with the returned value:


  • 如果您需要获取用于声明枚举常量的确切名称,则应使用 name()因为 toString 可能已被覆盖

  • 如果要以用户友好的方式打印枚举常量,则应使用 toString 可能已被覆盖(或不!)。

  • If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overriden
  • If you want to print the enum constant in a user friendly way, you should use toString which may have been overriden (or not!).

当我觉得可能会令人困惑,我提供一个更具体的 getXXX 方法,例如:

When I feel that it might be confusing, I provide a more specific getXXX method, for example:

public enum Fields {
    LAST_NAME("Last Name"), FIRST_NAME("First Name");

    private final String fieldDescription;

    private Fields(String value) {
        fieldDescription = value;
    }

    public String getFieldDescription() {
        return fieldDescription;
    }
}

这篇关于Java枚举 - 为什么使用toString而不是名字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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