How to retrieve Enum name using the id?

前端 未结 11 1701
一整个雨季
一整个雨季 2020-12-05 13:11

I have the enum as:

public enum EnumStatus {

    PASSED(40L, \"Has Passed\"),
    AVERAGE(60L, \"Has Average Marks\"),
    GOOD(80L, \"Has Good         


        
11条回答
  •  忘掉有多难
    2020-12-05 14:01

    This pattern can help you:

    public interface Identifiable {
    
        @Nonnull
        T getId();
    }
    
    public final class GettableById & Identifiable> {
    
        @Nonnull
        private final Map idToValue;
    
    
        public GettableById(@Nonnull V[] values) {
            this.idToValue = Arrays.stream(values)
                    .collect(Collectors.toUnmodifiableMap(Identifiable::getId, v -> v));
        }
    
        @Nonnull
        public V getById(@Nonnull K id) {
            var value = idToValue.get(id);
            if (value != null) {
                return value;
            }
            throw new NullPointerException("Cannot get value by id: %s".formatted(id));
        }
    }
    
    public enum DataType implements Identifiable {
    
        ANNUAL((short) 1), QUARTERLY((short) 2);
    
        private static final GettableById companion = new GettableById<>(values());
    
        @Nonnull
        private final Short id;
    
    
        public static DataType getById(Short id) {
            return companion.getById(id);
        }
    
        DataType(@Nonnull Short id) {
            this.id = id;
        }
    
        @Nonnull
        @Override
        public Short getId() {
            return id;
        }
    }
    

提交回复
热议问题