Java: enum values() and valueOf(String)

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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?

What I mean is, if I have some enum such as

enum FooEnum {ONE, TWO} 

javac adds values() and valueOf(String) to FooEnum when compiling it. I find it a bit odd. What is the reason behind this?

Is it only to ensure type safety of the returned value/values or is there anything else? And if it's for type safety alone, wouldn't Generics have helped?

回答1:

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.



回答2:

Why does javac add values() and valueOf(String) methods to the enum type being defined?

This keeps the class self contained.

Wouldn't it have been better that they were added to Enum class itself?

The compiler can't do this as the Enum class has already been compiled and you might not be using the same copy in any case.

This could be done at runtime but you add complexity e.g. it makes unloading the class more difficult for little gain.

What is the reason behind this?

There is no better place to put it.

Note: Enum.valueOf(clazz, name) calls clazz.valueOf(name); as it wouldn't make any sense to call a clazz.valueOf(clazz, name); (though you can if you want to confuse people)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!