我刚刚注意到 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/