Java 根据值获取枚举的名称

Java 根据值获取枚举的名称,java,Java,我有下面的枚举 public enum AppointmentSlotStatusType { INACTIVE(0), ACTIVE(1); private int value; private AppointmentSlotStatusType(int value) { this.value = value; } public int getValue() { return value; } p

我有下面的枚举

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中的值已知,如何获取枚举名称?

您可以维护一个映射来保存整数键的名称

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);
    }
}
看看这个。

您可以在枚举中实现一个公共静态方法,它将为您提供该id的枚举实例:

public static AppointmentSlotStatusType forId(int id) {
    for (AppointmentSlotStatusType type: values()) {
        if (type.value == id) {
            return value;
        }
    }
    return null;
}
您可能还希望缓存由字段中的值返回的数组:

public static final AppointmentSlotStatusType[] VALUES = values();
然后使用值而不是值

或者你可以用地图代替


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

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

实现valueOf style方法。在您看来,该方法真的应该返回null还是引发异常?如果要缓存,请使用映射-这是O1而不是On…@SotiriosDelimanolis我想在这里返回null没有问题。为什么不投票将其作为副本关闭?你认为这个问题和你链接到的问题有什么不同?我想补充一点,数字字段是无用的,因为已经有一个序数字段了。@Boristeider出于各种原因使用序数是个坏主意。
String name = TimeUnit.values()[1].name();