我宣布枚举为:
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函数只列出枚举的所有值.
NPE*_*NPE 34
隐式定义该方法(即由编译器生成).
来自JLS:
此外,如果
E是enum类型的名称,则该类型具有以下隐式声明的static方法:Run Code Online (Sandbox Code Playgroud)/** * 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);
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添加了它们
笔记:
从不使用性别作为类名,很难阅读你的代码,我们在Java中使用Sex
当面对像这样的Java拼图时,我建议使用字节码反编译工具(我使用Andrey Loskutov的字节码大纲Eclispe插件).这将显示课程内的所有内容