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

问题描述 投票:4回答:3

我有一个java Enum类,在运行时我将从命令行读取一个值,我想将此值与我的Enum类中的值对应。 Shipper是我的Enum Class。有没有更好的方法来做到这一点,而不是下面的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");
    }
}

这是我的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;
    }
}
java enums
3个回答
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);  
    }   
}

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

EnumWithValueOf enumRepresentation = EnumWithValueOf.textValueOf("a");

5
投票
shipperName.add(Shipper.valueOf(s.toUpperCase()));

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

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

3
投票

您可以从valueOf()方法获取Enum:

public void init(String s) {
    try {
        Shipper shipper = Shipper.valueOf(s.toUpperCase());

        shipperName.add(shipper);
    } catch(IllegalArgumentException e) {
        e.printStackTrace();
    }
}

编辑:

如果它不仅仅是一个简单的 - >一个案例,那么创建一个带有key => value对的HashMap可能是个主意:

private HashMap<String, Shipper> map;

public void init(String s) {
    if(map == null) {
        map = new HashMap<String, Shipper>();
        map.put("a", Shipper.A);
        ... //b => B code etc
    }

    if(map.containsKey(s)) {
        shipperName.add(map.get(s));
    } else {
        System.out.println("Error");
    }
}

我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.