[英]What is the point of the static valueOf() method? (enumerations)
我正在學習枚舉,我不明白這種方法的用途。
例:
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; !?
}
valueOf
方法的目的是為您提供一種獲取作為String
呈現給程序的Fruits
值的方法 - 例如,當值來自配置文件或用戶輸入時:
String fruitName = input.next();
Fruits fruit = Fruits.valueOf(fruitName);
上面,水果的名稱由最終用戶提供。 您的程序可以讀取並處理它作為enum
,而不知道在運行時將提供哪些水果。
我同意@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()方法將拋出運行時異常,而不是返回null。 例外情況是:
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.