Enum的values()方法的文档在哪里?

rai*_*mar 168 java enums

我宣布枚举为:

enum Sex {MALE,FEMALE};
Run Code Online (Sandbox Code Playgroud)

然后,迭代枚举,如下所示:

for(Sex v : Sex.values()){
    System.out.println(" values :"+ v);
}
Run Code Online (Sandbox Code Playgroud)

我检查了Java API但找不到values()方法?我很好奇这个方法来自哪里?

API链接:https: //docs.oracle.com/javase/8/docs/api/java/lang/Enum.html

Den*_*ret 175

您无法在javadoc中看到此方法,因为它是由编译器添加的.

记录在三个地方:

编译器在创建枚举时会自动添加一些特殊方法.例如,它们有一个静态值方法,该方法返回一个数组,该数组按照声明的顺序包含枚举的所有值.此方法通常与for-each构造结合使用,以迭代枚举类型的值.

  • Enum.valueOfclass
    (values方法描述中提到了特殊的隐式valueOf方法)

枚举类型的所有常量都可以通过调用该类型的隐式公共静态T [] values()方法来获得.

values函数只列出枚举的所有值.

  • 因为只使用标准机制(没有枚举),所以你不能使用这种静态方法.必须扩展java规范以允许这些枚举,这就是它必须由编译器添加的原因. (10认同)
  • 有什么具体的原因吗?为什么它不是API的一部分? (6认同)
  • 从Java 7开始,这已添加到java.lang.Enum的javadoc中,在静态valuOf方法的描述中. (4认同)
  • @androiddeveloper它返回一个新数组(否则你可能会弄乱枚举) (3认同)
  • 调用"values()"会创建一个新数组,还是重新使用相同的数组? (2认同)

NPE*_*NPE 34

隐式定义该方法(即由编译器生成).

来自JLS:

此外,如果Eenum类型的名称,则该类型具有以下隐式声明的static方法:

/**
* 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)


Evg*_*eev 12

运行这个

    for (Method m : sex.class.getDeclaredMethods()) {
        System.out.println(m);
    }
Run Code Online (Sandbox Code Playgroud)

你会看见

public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()
Run Code Online (Sandbox Code Playgroud)

这些都是"性"类所具有的公共方法.它们不在源代码中,javac.exe添加了它们

笔记:

  1. 从不使用性别作为类名,很难阅读你的代码,我们在Java中使用Sex

  2. 当面对像这样的Java拼图时,我建议使用字节码反编译工具(我使用Andrey Loskutov的字节码大纲Eclispe插件).这将显示课程内的所有内容