2009-08-12 17 views
7

Jede Java-Enumeration eine statische Werte hat() -Methode wie diese jedoch Wo ist Enum.values ​​() definiert?

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

verwendet werden kann, kann ich nicht herausfinden, wo diese Methode definiert ist. Es gibt keine Erwähnung davon in der Javadoc und es erscheint nirgendwo in der Quelldatei.

Antwort

9

definiert ist durch die Java Language Specification erforderlich:

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

Diese Methoden werden hinzugefügt während der Kompilierung, so dass, wenn Sie verwenden: values und valueOf für alle Aufzählungen wird implizit deklariert javap den Code zu zerlegen, können Sie tatsächlich auf ihren Körper schauen.

2

Es ist nicht explizit definiert, genau wie length Eigenschaft von Java-Array ist nicht definiert. Es steht implizit für den konkreten Enum-Typ zur Verfügung.

Verwandte Themen