- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
在 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)
来自哪里?它是语言的一个特性,即编译器内置的特性吗?
最佳答案
此方法由编译器隐式定义。
来自文档:
Note that for a particular enum type T, the implicitly declared public static T valueOf(String) method on that enum may be used instead of this method to map from a name to the corresponding enum constant. All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.
来自 Java Language Specification, section 8.9.2 :
In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:
/**
* 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);
关于java - Enum.valueOf(String) 方法从何而来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11914792/
我是一名优秀的程序员,十分优秀!