java - 覆盖 Enum#toString 不可取?

标签 java enums

我刚刚注意到 Enum#toString javadoc状态(强调我的):

Returns the name of this enum constant, as contained in the declaration. This method may be overridden, though it typically isn't necessary or desirable. An enum type should override this method when a more "programmer-friendly" string form exists.

默认情况下,toString()name()返回相同的东西,所以即使 toString 被覆盖,仍然可以通过 name() 方法访问枚举的名称。

有人知道为什么不希望覆盖 Enum#toString 吗?

编辑:供引用,name() 的 javadoc(重点与原文相同):

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 方法时,人们通常会期望返回名称,因此覆盖 toString 方法会返回一些意想不到的结果。

关于java - 覆盖 Enum#toString 不可取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10853206/

相关文章:

java - 正确设计一个类,连接到 SMTP 服务器、验证并发送消息(使用 JavaMail API)

java - 无符号短字节数组

java - 如何删除 Volley 中特定的 json feed 缓存? clear() 有效,但删除(url) 无效

c# - 将值解析为可为空的枚举

c# - 同步参照完整性表和枚举

swift - 原始类型 'Bool' 不能用任何文字表达

java - 无法将 int 传递给 setMessage(String) 方法

java - 想要一个引用对象吗?范围适用于中间对象吗?

c++ - `typedef enum {} t` 是否允许 C++0x 中的作用域枚举元素标识符?

java - 检索 Enum 的标签以形成列表