Why would an Enum implement an Interface?

前端 未结 16 2708
长发绾君心
长发绾君心 2020-11-28 01:34

I just found out that Java allows enums to implement an interface. What would be a good use case for that?

16条回答
  •  無奈伤痛
    2020-11-28 01:50

    There is a case I often use. I have a IdUtil class with static methods to work with objects implementing a very simple Identifiable interface:

    public interface Identifiable {
        K getId();
    }
    
    
    public abstract class IdUtil {
    
        public static  & Identifiable, S> T get(Class type, S id) {
            for (T t : type.getEnumConstants()) {
                if (Util.equals(t.getId(), id)) {
                    return t;
                }
            }
            return null;
        }
    
        public static  & Identifiable, S extends Comparable> List getLower(T en) {
            List list = new ArrayList<>();
            for (T t : en.getDeclaringClass().getEnumConstants()) {
                 if (t.getId().compareTo(en.getId()) < 0) {
                     list.add(t);
                }
            }
            return list;
        }
    }
    

    If I create an Identifiable enum:

        public enum MyEnum implements Identifiable {
    
            FIRST(1), SECOND(2);
    
            private int id;
    
            private MyEnum(int id) {
                this.id = id;
            }
    
            public Integer getId() {
                return id;
            }
    
        }
    

    Then I can get it by its id this way:

    MyEnum e = IdUtil.get(MyEnum.class, 1);
    

提交回复
热议问题