-------------------------------------- Java Sag is under construction: How do I get enum constant value corresponds to a string?
Please inform us if you find a non good advertisement : info.enim dot gmail.com

Best Web Hosting

dimanche 6 mai 2012

How do I get enum constant value corresponds to a string?

The valueOf() method of an enum type allows you to get an enum constant that the value corresponds to the specified string. When we pass a string that not available in the enum an exception will be thrown.
package org.kodejava.example.fundametal;

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public class EnumValueOfTest {
    public static void main(String[] args) {
        //
        // Using valueOf() method we can get an enum constant whose
        // value corresponds to the string passed as the parameter.
        //
        Day day = Day.valueOf("SATURDAY");
        System.out.println("Day = " + day);
        day = Day.valueOf("WEDNESDAY");
        System.out.println("Day = " + day);

        try {
            //
            // The following line will produce an exception because the
            // enum type does not contains a constant named JANUARY.
            //
            day = Day.valueOf("JANUARY");
            System.out.println("Day = " + day);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire

Best Web Hosting