简体   繁体   English

静态valueOf()方法有什么意义? (枚举)

[英]What is the point of the static valueOf() method? (enumerations)

I am learning about enumerations and I don't understand the purpose this method serves. 我正在学习枚举,我不明白这种方法的用途。

Example: 例:

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; !?

}    

The point of valueOf method is to provide you a way of obtaining Fruits values presented to your program as String s - for example, when values come from a configuration file or a user input: valueOf方法的目的是为您提供一种获取作为String呈现给程序的Fruits值的方法 - 例如,当值来自配置文件或用户输入时:

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

Above, the name of the fruit is provided by end-user. 上面,水果的名称由最终用户提供。 Your program can read and process it as an enum , without knowing which fruit would be supplied at run-time. 您的程序可以读取并处理它作为enum ,而不知道在运行时将提供哪些水果。

I agree with @dasblinkenlight, You can use Enum.valueOf() method If you have some runtime input. 我同意@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

One more thing I want to add here, If the enum doesn't exist for this input, then It valueOf() method will throw a Runtime exception, instead of returning null. 还有一件事我想在这里添加,如果此输入不存在枚举,则valueOf()方法将抛出运行时异常,而不是返回null。 The exception will be: 例外情况是:

Exception in thread "main" java.lang.IllegalArgumentException: No enum constant

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM