简体   繁体   中英

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:

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.

I agree with @dasblinkenlight, You can use Enum.valueOf() method If you have some runtime input.

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. The exception will be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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