问题描述
为什么javac为定义的枚举类型添加 values()
和 valueOf(String)
方法?我们的意思是,如果我有一些枚举,例如
Why does javac add values()
and valueOf(String)
methods to the enum type being defined? Wouldn't it have been better that they were added to Enum class itself?
b
enum FooEnum {ONE, TWO}
javac将 values()
和 valueOf(String)
添加到 FooEnum
编译时。我觉得有点奇怪这是什么原因?
javac adds values()
and valueOf(String)
to FooEnum
when compiling it. I find it a bit odd. What is the reason behind this?
只是为了确保返回的值/值的类型安全性,还是有其他的?如果是单独的类型安全,泛型将不会有帮助?
推荐答案
他们是静态方法 - 如何将它们添加到枚举
?静态方法不是多态的。另外,在您提出的方案中,执行在枚举
中看起来如何? 枚举
本身不知道值 - 只有具体的类型。
They're static methods - how could they have been added to Enum
? Static methods aren't polymorphic. Additionally, what would the implementation have looked like in Enum
, in your proposed scheme? Enum
itself doesn't know the values - only the concrete type does.
这篇关于Java:枚举值()和valueOf(String)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!