繁体   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