![](/img/trans.png)
[英]enum.valueOf(String name) missing from Javadoc 1.5 and 1.6
[英]Where does the Enum.valueOf(String) method come from?
在Java SE 7中(並且很可能在以前的版本中),Enum類的聲明如下:
public abstract class Enum<E extends Enum<E>>
extends Object
implements Comparable<E>, Serializable
Enum類具有帶有此簽名的靜態方法:
T static<T extends Enum<T>> valueOf(Class<T> enumType, String name)
但是沒有靜態方法:在Enum類中定義的valueOf(String)
也不在Enum所屬的層次結構中。
問題是valueOf(String)
來自哪里? 它是語言的功能,即編譯器內置的功能嗎?
該方法由編譯器隱式定義。
從文檔中:
請注意,對於特定的枚舉類型T,可以使用對該枚舉上隱式聲明的公共靜態T valueOf(String)方法來代替此方法,以從名稱映射到相應的枚舉常量。 可以通過調用該類型的隱式公共靜態T [] values()方法來獲取枚舉類型的所有常量。
根據Java語言規范的第8.9.2節 :
此外,如果E是枚舉類型的名稱,則該類型具有以下隱式聲明的靜態方法:
/**
* 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);
我認為這一定是語言的特色。 對於一個,通過創建一個來創建枚舉,並且不需要擴展Enum:
public enum myEnum { red, blue, green }
僅此一項是語言功能,否則您需要這樣做:
public class MyEnum extends Enum { ..... }
其次,當您使用myEnum.valueOf(String name)
時,編譯器必須產生Enum.valueOf(Class<T> enumType, String name)
myEnum.valueOf(String name)
。
鑒於新的Enum
既是語言功能又是擴展類,這似乎是可能的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.