2012-08-11 33 views
22

在Java SE 7(最可能是在以前的版本)的枚舉類被聲明如下:Enum.valueOf(String)方法來自哪裏?

public abstract class Enum<E extends Enum<E>> 
extends Object 
implements Comparable<E>, Serializable 

的枚舉類有與此簽名靜態方法:

T static<T extends Enum<T>> valueOf(Class<T> enumType, String name) 

但有沒有靜態方法:在Enum類中定義的valueOf(String)也不在Enum所屬的層次結構中。

問題是valueOf(String)從何而來? 它是該語言的一個功能,即編譯器中內置的功能?

回答

21

該方法由編譯器隱式定義。

從文檔:

注意,對於一個特定的枚舉類型T,隱式聲明上該枚舉公共靜態Ť的valueOf(String)方法可以代替地使用這種方法來從一個名稱映射到相應的枚舉常量。枚舉類型的所有常量可以通過調用該類型的隱式公共靜態T [] values()方法來獲得。

Java Language Specification, section 8.9.2

此外,如果E是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); 
+0

在Enum類的一組方法中不包含此方法的原因是,在編譯時,當返回的Enum值已知(即:由該類定義的類型的枚舉對象程序員)。 不過,另一種方法是將其實際聲明爲Enum類中的抽象方法,並讓編譯器在編譯時提供實現。當然,這意味着它也可以被用戶覆蓋,但編譯器也可以處理這種情況。 在課堂上使用這種方法看起來更自然! – Razvan 2012-08-11 13:15:46

+2

@Razvan靜態方法不能在Java中抽象(或者大多數其他語言,我想)。 – sepp2k 2012-08-11 13:20:09

+0

我沒有說靜態抽象! – Razvan 2012-08-11 15:52:11

0

我認爲它必須是該語言的一個特徵。其一,通過使一個創建一個枚舉,它並不需要擴展Enum:

public enum myEnum { red, blue, green } 

這僅僅是一個語言功能,否則你就需要這樣做:

public class MyEnum extends Enum { ..... } 

其次,當您使用myEnum.valueOf(String name)時,必須由編譯器生成方法Enum.valueOf(Class<T> enumType, String name)

這是看起來可能的,因爲新的Enum是一種語言功能,因爲它是一個擴展類。