2009-08-12 9 views
7

wyliczenie Każdy Java ma statyczny wartości() metoda może być używany jak togdzie jest zdefiniowana wartość Enum.values ​​()?

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

Jednak nie mogę dowiedzieć się, gdzie metoda ta jest zdefiniowana. Nie ma o nim wzmianki w numerze Javadoc i nie pojawia się nigdzie w pliku źródłowym.

Odpowiedz

9

ta jest wymagana przez Java Language Specification: values i valueOf zostaną niejawnie zadeklarowana dla wszystkich wyliczenia:

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

Te metody są dodawane podczas kompilacji, więc jeśli używasz javap, aby zdemontować kod, możesz rzeczywiście spojrzeć na swoje ciało.

2

Nie jest to jednoznacznie zdefiniowane, podobnie jak własność tablicy java nie jest zdefiniowana. Jest on domyślnie dostępny dla konkretnego typu Enum.