Enum.valueOf(String)方法来自哪里?
在Java SE 7中(最有可能在以前的版本中),Enum类声明如下:
public abstract class Enum<E extends Enum> extends Object implements Comparable, Serializable
Enum类有一个带有此签名的静态方法:
T static<T extends Enum> valueOf(Class enumType, String name)
但是没有静态方法:在Enum类中定义的valueOf(String)
也不在Enum所属的层次结构中向上。
问题是valueOf(String)
来自哪里? 它是语言的一个特性,即编译器内置的function吗?
此方法由编译器隐式定义。
从文档:
请注意,对于特定的枚举类型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);
我认为它必须是该语言的一个特征。 首先,通过创建枚举来创建枚举,它不需要扩展枚举:
public enum myEnum { red, blue, green }
仅此一项是语言function,否则您需要这样做:
public class MyEnum extends Enum { ..... }
其次,当您使用myEnum.valueOf(String name)
时,编译器必须生成方法Enum.valueOf(Class
myEnum.valueOf(String name)
。
这似乎是可能的,因为新的Enum
既是一个语言特性,也是一个扩展的类。