12 April 2011

How to convert enum string to enum in java ?

Solution for java 5 ,java 6  (Enum doesn't exist in java 4 and below)

If you want  convert enum string to enum in java you need use valueOf method like:

NameOfEnumType.valueOf(StringToConvert.toUpperCase());
    where:
    •  NameOfEnumType - An enum type (like class name )
    •  StringToConvert - string that will be converted to Enum
    •  toUpperCase() - is optional but by convention fields names are upper case,so this method will automatically convert to uppercase
    for example:

    Enum:

    public enum Visa {
    ALL,
    WORK,
    SLAVERY
    STUDY,
    NONE 
    }

    so now, in place, where you need convert where you will  use method like
    String visatype = "terrorist";
    try{
    result = BorderAgency.isLegal();
    }catch(IllegalArgumentException iae){
    sendCitizenToJail(Visa.valueOf(visatype.toUpperCase()));
    }

    Source: http://download.oracle.com/javase/tutorial/java/javaOO/enum.html