2016-06-14 66 views
1

我正在學習枚舉,我不明白這個方法服務的目的。靜態valueOf()方法的要點是什麼? (枚舉)

實施例:

enum Fruits{ 
    apple, pear, orange 
} 

class Demo{ 
    f = Fruits.valueOf("apple"); //returns apple... but I had to type it! 
           // so why wouldn't I save myself some time 
           // and just write: f = Fruits.apple; !? 

}  
+3

也許你收到了字符串''蘋果''作爲用戶輸入,並想嘗試將其解析爲枚舉元素? – JonK

+0

一個例子是序列化的文本消息(例如JSON),其中一個值是枚舉元素的表示。爲了反序列化一個實際的enum元素,使用'valueOf'會有意義。 – Mena

回答

2

valueOf方法的要點在於,提供你獲得呈現給你的程序作爲String小號Fruits值的方式 - 例如,當值來自配置文件或用戶輸入:

String fruitName = input.next(); 
Fruits fruit = Fruits.valueOf(fruitName); 

以上,水果的名稱由最終用戶提供。您的程序可以將其作爲enum進行讀取和處理,但不知道運行時將提供哪些水果。

1

我同意@dasblinkenlight,你可以使用Enum.valueOf()方法如果你有一些運行時輸入。

String input="apple" //It may be passed from some where 
Fruits fruit = Fruits.valueOf(input); // Here you will get the object of type Fruits 

還有一兩件事我想在這裏補充,如果枚舉沒有此輸入存在,那麼它的valueOf()方法將拋出而不是返回空運行時異常。例外將是:

Exception in thread "main" java.lang.IllegalArgumentException: No enum constant 
相關問題