Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum and if statement, is there a better way to do this?

Tags:

java

enums

I have an java Enum class, and at runtime I will read in a value from command line, and I want to correspond this value to a value in my Enum class. Shipper is my Enum Class. Is there a better way do this this, instead of if and else if below? This look ugly.

private List<Shipper> shipperName = new ArrayList<Shipper>();
...
public void init(String s){ 
    if(s.equals("a")){
        shipperName.add(Shipper.A);
    }else if(s.equals("b")){
        shipperName.add(Shipper.B);
    }else if(s.equals("c")){
        shipperName.add(Shipper.C);
    }else if(s.equals("d")){
        shipperName.add(Shipper.D);
    }else if(s.equals("e")){
        shipperName.add(Shipper.E);
    }else{
        System.out.println("Error");
    }
}

Here is my Shipper.class

public enum Shipper
{
    A("a"),
    B("b"),
    C("c"),
    D("e"),
    F("f")
;

    private String directoryName;

    private Shipper(String directoryName)
    {
         this.directoryName = directoryName;
    }

    public String getDirectoryName()
    {
         return directoryName;
    }
}
like image 444
Thang Pham Avatar asked May 12 '11 19:05

Thang Pham


1 Answers

Yes add the string into the enum's constructor (specify a constructor in the enum which takes a String) and create the enums with a text value of a, b , c. Etc. Then implement a static factory method on the enum which takes a string and returns the enum instance. I call this method textValueOf. The existing valueOf method in enum cannot be used for this. Something like this:

public enum EnumWithValueOf {

    VALUE_1("A"), VALUE_2("B"), VALUE_3("C");

    private  String textValue;

    EnumWithValueOf(String textValue) {
        this.textValue = textValue;
    }

    public static EnumWithValueOf textValueOf(String textValue){

        for(EnumWithValueOf value : values()) {
            if(value.textValue.equals(textValue)) {
                return value;
            }
        }

        throw new IllegalArgumentException("No EnumWithValueOf
                            for value: " + textValue);  
    }   
}

This is case insensitive and the text value can be different to the enum name - perfect if your database codes are esoteric or non descriptive, but you want better names in the Java code. Client code then do:

EnumWithValueOf enumRepresentation = EnumWithValueOf.textValueOf("a");
like image 138
planetjones Avatar answered Nov 03 '22 00:11

planetjones