簡體   English   中英

靜態valueOf()方法有什么意義? (枚舉)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM