Java: enum () and valueOf (String) values

Why does javac add the values() and valueOf(String) methods to a specific type of enumeration? Isn't it better that they be added to the Enum class?

What do I mean if I have an enumeration such as

 enum FooEnum {ONE, TWO} 

javac adds values() and valueOf(String) to FooEnum when compiling. I find it a little strange. What is the reason for this?

Is it just for security like return values ​​/ values ​​or is there something else? And if it's for type safety alone, would Generics not help?

+6
source share
2 answers

They are static methods - how could they be added to Enum ? Static methods are not polymorphic. In addition, what would be implemented in Enum in your proposed scheme? Enum itself does not know the values ​​- only a specific type does.

+6
source

Why does javac add values ​​() and valueOf (String) methods to a specific type of enumeration?

This saves the class itself.

Wouldn't it be better if they were added to the Enum class?

The compiler cannot do this, since the Enum class is already compiled, and you may not use the same copy anyway.

This can be done at runtime, but you add complexity, for example. this makes class unloading more difficult for little gain.

What is the reason for this?

There is no better place to place it.

Note: Enum.valueOf(clazz, name) calls clazz.valueOf(name); , since it would be pointless to call clazz.valueOf(clazz, name); (although you can if you want to confuse people)

+6
source

Source: https://habr.com/ru/post/926815/


All Articles