【问题标题】:Where does the Enum.valueOf(String) method come from?Enum.valueOf(String) 方法从何而来?
【发布时间】:2012-08-11 12:40:08
【问题描述】:

在 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) 来自哪里? 它是语言的一个特性,即编译器内置的特性吗?

【问题讨论】:

    标签: java compiler-construction enums value-of


    【解决方案1】:

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

    来自文档:

    请注意,对于特定的枚举类型 T,可以使用该枚举上隐式声明的 public static T valueOf(String) 方法而不是此方法来从名称映射到相应的枚举常量。枚举类型的所有常量都可以通过调用该类型的隐式 public static T[] values() 方法获得。

    来自Java Language Specification, section 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);
    

    【讨论】:

    • Enum 类的方法集中不包含该方法的原因是,直到编译时,返回的 Enum 值已知(即:程序员定义的类型)。不过,另一种方法是在 Enum 类中将其实际声明为抽象方法,并让编译器在编译时提供实现。当然,这意味着它也可以被用户覆盖,但编译器也可以处理这种情况。在类中有方法看起来更自然!
    • @Razvan 静态方法在 Java(或大多数其他语言,我想)中不能是抽象的。
    • 我没有说静态摘要!
    • @Razvan 你没有说静态,但它们静态的。您是否建议将它们更改为非静态的?这不会削弱那里的用处吗?
    • @sepp2k 肯定会,因为您必须首先构建一个 Enum 的实例,然后调用 valueOf。我的建议是在类中,在代码中使用该方法。另一种选择是有一个没有实现的静态方法,编译器应该在编译时提供实现。
    【解决方案2】:

    我认为这一定是语言的一个特点。其一,通过生成一个来创建一个枚举,它不需要扩展枚举:

    public enum myEnum { red, blue, green }
    

    仅此一项,就是语言功能,否则您需要这样做:

    public class  MyEnum extends Enum { ..... }
    

    其次,方法Enum.valueOf(Class&lt;T&gt; enumType, String name)必须在您使用myEnum.valueOf(String name)时由编译器生成。

    鉴于新的Enum 既是一种语言特性,又是一个需要扩展的类,这似乎是可能的。

    【讨论】:

      猜你喜欢
      • 2018-11-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多