Enum.valueOf(String)方法来自哪里?

Raz*_*van 26 java compiler-construction enums value-of

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

 public abstract class Enum<E extends Enum<E>>
 extends Object
 implements Comparable<E>, Serializable
Run Code Online (Sandbox Code Playgroud)

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

  T static<T extends Enum<T>> valueOf(Class<T> enumType, String name) 
Run Code Online (Sandbox Code Playgroud)

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

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

das*_*ght 23

此方法由编译器隐式定义.

从文档:

请注意,对于特定的枚举类型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);
Run Code Online (Sandbox Code Playgroud)

  • 在Enum类的方法集中不包含此方法的原因是,直到已知返回的Enum值的编译时(即:程序员定义的类型的enum对象),才提供实现。仍然可以选择在Enum类中将其实际声明为抽象方法,并让编译器在编译时提供实现。当然,这意味着它也可以被用户覆盖,但是编译器也可以处理这种情况。在类中拥有该方法看起来更自然! (2认同)
  • @Razvan静态方法不能用Java(或者大多数其他语言,我想)来抽象. (2认同)