简体   繁体   中英

Getting enum value by passing preset ordinal

I have looked this link : Convert from enum ordinal to enum type

and tried to get the enum value. But is not working. My enum class is :

public enum OrderStatus {

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

I will pass the values 0,1,3,4 where 2 is missing , so it has no such order. How to get enum by passing 0,1,3 or 4 in groovy or java.

Add a field to the enum, and a constructor:

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)
}

and then you can define a method like this:

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

Record the value in the enum and build a Map to convert.

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

Just declare a field inside enum as you do in class. And provide a getter method for the field:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM