Java枚举和if语句,有更好的方法吗?

Tha*_*ham 5 java enums

我有一个java Enum类,在运行时我将从命令行读取一个值,我想将此值与我的Enum类中的值对应.Shipper是我的Enum课程.有没有更好的办法做到这一点这个,而不是ifelse if下面?这看起来很难看.

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

pla*_*nes 6

是将字符串添加到枚举的构造函数中(在枚举中指定一个带有String的构造函数)并创建文本值为a,b,c的枚举.等等.然后在枚举上实现一个静态工厂方法,它接受一个字符串并返回枚举实例.我将此方法称为textValueOf.枚举中的现有valueOf方法不能用于此.像这样的东西:

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);  
    }   
}
Run Code Online (Sandbox Code Playgroud)

这是不区分大小写的,文本值可以与枚举名称不同 - 如果您的数据库代码是深奥的或非描述性的,但是您希望Java代码中有更好的名称,则这是完美的.然后客户端代码执行:

EnumWithValueOf enumRepresentation = EnumWithValueOf.textValueOf("a");
Run Code Online (Sandbox Code Playgroud)


Jus*_*KSU 5

shipperName.add(Shipper.valueOf(s.toUpperCase()));
Run Code Online (Sandbox Code Playgroud)

如果名称并不总是与枚举匹配,则可以执行此类操作

public static Shipper getShipper(String directoryName) {
    for(Shipper shipper : Shipper.values()) {
        if(shipper.getDirectoryName().equals(directoryName)) {
            return shipper;
        }
    }
    return null; //Or thrown exception
}
Run Code Online (Sandbox Code Playgroud)