将Java枚举映射为整数

时间:2019-03-11 16:14:02

标签: java enums integer

我想将整数映射到Java中的枚举。整数必须是键,而枚举是值。我见过的所有示例都将枚举作为值,将整数作为键。我有:

enum CardStatus {
    UNKNOWN, // 0 should map to this
    PENDING, // 1 should map to this
    ACTIVE // 2 should map to this

    public CardStatus getCardStatus(int cardStatus) {
        // e.g. cardStatus of 1 would return PENDING
    }
}

如何调用getCardStatus()并返回一个CardStatus枚举?例如。 getCardStatus(2)将返回ACTIVE

1 个答案:

答案 0 :(得分:4)

您可以将getCardStatus()设为静态:

enum CardStatus {
    UNKNOWN, // 0 should map to this
    PENDING, // 1 should map to this
    ACTIVE; // 2 should map to this

    public static CardStatus getCardStatus(int cardStatus) {
        return CardStatus.values()[cardStatus];
    }
}

并使用它:

System.out.println(CardStatus.getCardStatus(0));