通过传递预设序数获取枚举值

时间:2015-09-24 10:20:14

标签: java groovy enums

我看过这个链接:Convert from enum ordinal to enum type

并尝试获取枚举值。但是没有用。我的enum课程是:

public enum OrderStatus {

    OPEN(0),
    DELIVERED(1),
    CANCELLED(3),
    PARTIALLY(4)
}

我将传递值0,1,3,4,其中2缺失,因此它没有这样的顺序。如何通过在groovy或java中传递0,1,3或4来获取枚举。

3 个答案:

答案 0 :(得分:2)

在枚举和构造函数中添加一个字段:

public enum OrderStatus {
    private Integer codice;

    public Integer getCodice() {
        return codice;
    }

    private OrderStatus(Integer codice) {
        this.codice = codice;
    }

    OPEN(0),
    DELIVERED(1),
    CANCELLED(3),
    PARTIALLY(4)
}

然后你可以定义一个这样的方法:

public static OrderStatus getByCodice(int codice) {
    for (OrderStatus tipo : values()) {
        if (tipo.codice == codice) {
            return tipo;
        }
    }
    throw new IllegalArgumentException("Invalid codice: " + codice);
}

答案 1 :(得分:1)

enum中记录值并构建一个Map进行转换。

public enum OrderStatus {

    OPEN(0),
    DELIVERED(1),
    CANCELLED(3),
    PARTIALLY(4);
    final int ordinal;

    private OrderStatus(int ordinal) {
        this.ordinal = ordinal;
    }

    static Map<Integer, OrderStatus> lookup = null;

    public static OrderStatus lookup(int ordinal) {
        // Could just run through the array of values but I will us a Map.
        if (lookup == null) {
            // Late construction - not thread-safe.
            lookup = Arrays.stream(OrderStatus.values())
                    .collect(Collectors.toMap(s -> s.ordinal, s -> s));
        }
        return lookup.get(ordinal);
    }
}

public void test() {
    for (int i = 0; i < 5; i++) {
        System.out.println(i + " -> " + OrderStatus.lookup(i));
    }
}

答案 2 :(得分:0)

只需像在课堂上那样在枚举中声明一个字段。并为该领域提供一个getter方法:

public enum OrderStatus 
{
    OPEN(0),
    DELIVERED(1), /*pass value*/
    CANCELLED(3),
    PARTIALLY(4);

    private int value; /*Add a field*/

    OrderStatus ( int value )
    {
        this.value = value;
    }

    /*Access with getter*/      
    int getValue ( )
    {
        return value;
    }
}