Enum.valueOf(String)方法从何而来?


问题内容

在Java SE 7中(并且很可能在以前的版本中),Enum类的声明如下:

 public abstract class Enum<E extends Enum<E>>
 extends Object
 implements Comparable<E>, Serializable

Enum类具有带有此签名的静态方法:

  T static<T extends Enum<T>> valueOf(Class<T> enumType, String name)

但是没有静态方法:valueOf(String)在Enum类中定义,也不在Enum所属的层次结构中。

问题是valueOf(String)从哪里来的?它是语言的功能,即编译器中内置的功能吗?


问题答案:

该方法由编译器隐式定义。

从文档中:

请注意,对于特定的枚举类型T,可以使用对该枚举上隐式声明的公共静态T
valueOf(String)方法来代替此方法,以从名称映射到相应的枚举常量。可以通过调用该类型的隐式公共静态T []
values()方法来获取枚举类型的所有常量。

根据Java语言规范的第8.9.2节

另外,如果E是枚举类型的名称,则该类型具有以下隐式声明的静态方法:

/**
* 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);