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?
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.
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)