Enum.values() 在哪里定义的?

发布于 2024-08-02 12:00:55 字数 283 浏览 0 评论 0原文

每个Java枚举都有一个静态values()方法,可以像这样使用

for (MyEnum enum : MyEnum.values()) {
    // Do something with enum
}

但是,我不知道这个方法是在哪里定义的。 Javadoc 中没有提及它它不会出现在源文件中的任何位置。

Every Java enumeration has a static values() method can be used like this

for (MyEnum enum : MyEnum.values()) {
    // Do something with enum
}

However, I cannot figure out where this method is defined. There's no mention of it in the Javadoc and it doesn't appear anywhere in the source file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

聚集的泪 2024-08-09 12:00:55

这是 Java 语言规范 所要求的: valuesvalueOf 将为所有 Enum 隐式声明:

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

这些方法是在编译时添加的,因此如果您使用 javap 反汇编代码,你实际上可以看看他们的身体。

This is required by the Java Language Specification: values and valueOf will be implicitly declared for all Enums:

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

These methods are added during compile time, so if you use javap to disassemble the code, you can actually look at their body.

疯了 2024-08-09 12:00:55

它没有明确定义,就像java数组的length属性没有定义一样。它隐式地可用于具体的 Enum 类型。

It's not explicitly defined, just like length property of java array is not defined. It is implicitly available for concrete Enum type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文