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;
}
}
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:
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: