关于Java:Enum的values()方法的文档在哪里?

Where is the documentation for the values() method of Enum?

我将枚举声明为:

1
enum Sex {MALE,FEMALE};

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

1
2
3
for(Sex v : Sex.values()){
    System.out.println(" values :"+ v);
}

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

API连结:
https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html


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

记录在三个地方:

  • 枚举类型,来自Java教程

The compiler automatically adds some special methods when it creates
an enum. For example, they have a static values method that returns an
array containing all of the values of the enum in the order they are
declared. This method is commonly used in combination with the
for-each construct to iterate over the values of an enum type.

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

All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.

  • 枚举类型,第8.9节,Java语言规范

values函数仅列出枚举的所有值。


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

从JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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);


运行这个

1
2
3
    for (Method m : sex.class.getDeclaredMethods()) {
        System.out.println(m);
    }

你会看见

1
2
public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()

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

笔记:

  • 从不使用性别作为类名,很难读取您的代码,我们在Java中使用性别

  • 当面对这样的Java难题时,我建议使用字节码反编译器工具(我使用Andrey Loskutov的字节码大纲Eclispe插件)。这将显示课程中的所有内容