2009-08-12 16 views
7

Cada Java enumeración tiene un valores estáticos() método se puede utilizar como estedonde se define Enum.values ​​()?

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

Sin embargo, no puedo averiguar dónde se define este método. No se menciona en el Javadoc y no aparece en ningún lugar del archivo fuente.

Respuesta

9

Esto es requerido por el Java Language Specification: values y valueOf será declarado implícitamente para todas las enumeraciones: se añaden

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

Estos métodos durante el tiempo de compilación, por lo que si se utiliza javap para desmontar el código, en realidad puedes mirar su cuerpo.

2

No está explícitamente definido, al igual que length no está definida la propiedad de la matriz Java. Está implícitamente disponible para el tipo concreto de Enum.

Cuestiones relacionadas