How can I eliminate duplicated Enum code?

后端 未结 15 826
眼角桃花
眼角桃花 2020-12-24 13:40

I have a large number of Enums that implement this interface:

/**
 * Interface for an enumeration, each element of which can be uniquely identified by its co         


        
15条回答
  •  囚心锁ツ
    2020-12-24 14:12

    In my opinion, this would be the easiest way, without reflection and without adding any extra wrapper to your enum.

    You create an interface that your enum implements:

    public interface EnumWithId {
    
        public int getId();
    
    }
    

    Then in a helper class you just create a method like this one:

    public  T getById(Class enumClass, int id) {
        T[] values = enumClass.getEnumConstants();
        if (values != null) {
            for (T enumConst : values) {
                if (enumConst.getId() == id) {
                    return enumConst;
                }
            }
        }
    
        return null;
    }
    

    This method could be then used like this:

    MyUtil.getInstance().getById(MyEnum.class, myEnumId);
    

提交回复
热议问题