Where does the Enum.valueOf(String) method come from?

馋奶兔 提交于 2019-11-28 21:11:50

This method is implicitly defined by the compiler.

From the documentation:

Note that for a particular enum type T, the implicitly declared public static T valueOf(String) method on that enum may be used instead of this method to map from a name to the corresponding enum constant. All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.

From the Java Language Specification, section 8.9.2:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);
The Coordinator

I think it must be a feature of the language. For one, to create an enum by making one and it does not need to extend Enum:

public enum myEnum { red, blue, green }

That alone, is a language feature or else you would need to do this:

public class  MyEnum extends Enum { ..... }

Secondly, the method, Enum.valueOf(Class<T> enumType, String name), must be produced by the compiler when you you use myEnum.valueOf(String name).

That is what would seem possible given that the new Enum is as much a language feature as it is a class to extend.

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