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

时间:2012-08-11 12:40:08

标签: java compiler-construction enums value-of

在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) 

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

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

2 个答案:

答案 0 :(得分:23)

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

来自文档:

  

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

来自Java Language Specification, section 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);

答案 1 :(得分:0)

我认为它必须是该语言的一个特征。首先,通过创建枚举来创建枚举,它不需要扩展枚举:

public enum myEnum { red, blue, green }

仅此一项是语言功能,否则你需要这样做:

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

其次,当您使用Enum.valueOf(Class<T> enumType, String name)时,编译器必须生成方法myEnum.valueOf(String name)

这似乎是可能的,因为新的Enum是一个语言特征,因为它是一个可以扩展的类。

相关问题