根据值获取枚举的名称

时间:2013-10-15 15:41:00

标签: java

我有以下枚举

public enum AppointmentSlotStatusType {

    INACTIVE(0), ACTIVE(1);

    private int value;

    private AppointmentSlotStatusType(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public String getName() {
        return name();
    }
}

如果已知某个值为1

,我如何获取枚举名称?

3 个答案:

答案 0 :(得分:6)

对于这个特定的枚举,这很容易

String name = TimeUnit.values()[1].name();

答案 1 :(得分:1)

您可以在public static中实现enum方法,该方法将为您提供该ID的枚举实例:

public static AppointmentSlotStatusType forId(int id) {
    for (AppointmentSlotStatusType type: values()) {
        if (type.value == id) {
            return value;
        }
    }
    return null;
}

您可能还希望将values()返回的数组缓存在字段中:

public static final AppointmentSlotStatusType[] VALUES = values();

然后使用VALUES代替values()


或者您可以使用Map代替。

private static final Map<Integer, AppointmentSlotStatusType> map = new HashMap<>();

static {
    for (AppointmentSlotStatusType type: values()) {
        map.put(type.value, type);
    }
}

public static AppointmentSlotStatusType forId(int id) {
    return map.get(id);
}

答案 2 :(得分:0)

您可以维护Map以保留Integer键的名称。

public enum AppointmentSlotStatusType {
    INACTIVE(0), ACTIVE(1);

    private int value;

    private static Map<Integer, AppointmentSlotStatusType> map = new HashMap<Integer, AppointmentSlotStatusType>();

    static {
        for (AppointmentSlotStatusType item : AppointmentSlotStatusType.values()) {
            map.put(item.value, item);
        }
    }

    private AppointmentSlotStatusType(final int value) { this.value = value; }

    public static AppointmentSlotStatusType valueOf(int value) {
        return map.get(value);
    }
}

看看这个answer

相关问题