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()方法来获得.
此外,如果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)
| 归档时间: |
|
| 查看次数: |
15993 次 |
| 最近记录: |