当前位置: 首页 > 面试题库 >

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

家浩瀚
2023-03-14
问题内容

在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)从哪里来的?它是语言的功能,即编译器中内置的功能吗?


问题答案:

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

从文档中:

请注意,对于特定的枚举类型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);


 类似资料:
  • 问题内容: 这可能是一个愚蠢的问题,但是我正在使用method 。那里没问题,只是当我检查javadoc以了解有关此方法的更多信息时,我找不到它。有Javadoc的,但没有一个 (这表明不存在具有此签名的方法- 但显然它存在)。 我在这里遗漏了什么吗,或者这是API的javadoc中的一个疏漏? 谢谢 问题答案: 没有方法Enum.valueOf(String)但是,每个方法都有一个由编译器生成的

  • 问题内容: 从名称(以String格式)中调用方法有时会很有用。 在Swift中,建议更改行为并使用闭包“动态”地进行操作,例如,您可以拥有一个函数字典,名称为键,实现为值。 但是,有时您只想简单地知道“怎么做”,这就是这个问题的原因。 那么,如何从名称作为字符串开始动态调用Swift方法? 在目标C中很简单: 但是在Swift中被禁止 还有其他选择吗? 问题答案: 在Swift中,您应该使用闭包

  • 问题内容: 改善这个问题 来自链接: http://www.tutorialspoint.com/java/java_string_hashcode.htm Java中的hashCode和equals方法之间的关系 好的hashCode()实现 但是我不了解哈希码。 这是一个例子: 这个简单的程序给我输出: 谁能告诉我:它是如何给我的输出:? 问题答案: 字符串的 哈希码 计算如下: 使用算术,其

  • 主要内容:Java12 indent(n)方法,transform(Function<? super String ? extends R> f) 方法,Optional<String> describeConstable() 方法,resolveConstantDesc (MethodHandles.Lookup lookup) 方法,Java12 String方法示例Java 12 为 String 引入了以下新方法,以便于格式化。 Java12 indent(n)方法 根据传递的参数调整每

  • 在下面的程序中,我将一个字符串值作为参数传递给方法print(string),该方法是静态的,返回string。虽然我没有得到错误,但我没有得到输出。

  • 问题内容: 我试图看一下Java的方法,但是 一般来说,实习如何实施?在String的情况下? 问题答案: 对于Sun Java,从的〜3639行开始。从技术上讲,实际的String方法在中,但会立即调用。您可以继续在。 从更抽象的意义上讲,实习的目的是将等效字符串映射到单个规范字符串。