14

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.

Dónal
  • 185,044
  • 174
  • 569
  • 824

3 Answers3

14

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.

andri
  • 11,171
  • 2
  • 38
  • 49
  • 1
    Hi, I'm curious on why the enum is designed like this? AFAIK, the most of the definition was inside the class in Java – Ninja Sep 10 '21 at 06:26
  • Does this mean that writing the bytecode could let you do hideous things like excluding a legacy enum value? – Ryan Leach Jan 20 '22 at 04:49
4

It's defined in the JLS, section 8.9.3 "Enum Members"

newacct
  • 119,665
  • 29
  • 163
  • 224
  • 2
    In the spirit of SO, I believe dropping a link to a giant pile of manuals is not terribly kind or helpful. – chrips Oct 28 '19 at 23:39
  • @Chrips: When the answer was posted, the link linked to a specific section of the Java Language Specification specifying the members of enums. The link no longer works. I will try to update it. – newacct Oct 29 '19 at 03:11
2

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

ChssPly76
  • 99,456
  • 24
  • 206
  • 195