gpt4 book ai didi

java - Enum.valueOf(String) 方法从何而来?

转载 作者:IT老高 更新时间:2023-10-28 21:19:40 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com