Java:枚举值()和valueOf(String) [英] Java: enum values() and valueOf(String)

查看:120
本文介绍了Java:枚举值()和valueOf(String)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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