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

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

问题描述

如果您查看 enum api 中的方法 name() 它说:

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 而不是 name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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