Enums shared static look-up method

前端 未结 2 1119
攒了一身酷
攒了一身酷 2020-12-25 12:49

I have the following Enum:

public enum MyEnum{
    A(10, \"First\"), //
    B(20, \"Second\"), //
    C(35, \"Other options\");

    private Integer code;
           


        
相关标签:
2条回答
  • 2020-12-25 13:34

    You need to pass the actual enum class object as a parameter to your method. Then you can get the enum values using Class.getEnumConstants().

    In order to be able to access getCode() on the instances, you should define it in an interface and make all your enum types implement that interface:

    interface Encodable {
        Integer getCode();
    }
    
    public static <T extends Enum<T> & Encodable> T getValueOf(Class<T> enumClass, Integer code) {
        for (T e : enumClass.getEnumConstants()) {
            if (e.getCode().equals(code)) {
                return e;
            }
        }
        throw new IllegalArgumentException("No enum const " + enumClass.getName() + " for code \'" + code
                + "\'");
    }
    
    ...
    
    public enum MyEnum implements Encodable {
        ...
    }
    
    MyEnum e = getValueOf(MyEnum.class, 10);
    
    0 讨论(0)
  • 2020-12-25 13:35

    This is a bit tricky because the values() method is static. You would actually need reflection, but there is a nice way to hide this using standard library functionality.

    First, define an interface with the methods common to all of your enum types:

    public interface Common {
        Integer getCode();
        String getDescription();
    }
    

    Then, make all your enums implement this interface:

    public enum MyEnum implements Common {...}
    

    The static method you want to have then looks like:

    public static <T extends Enum<T> & Common> T getValueOf( Class<T> type, Integer code ) {
        final EnumSet<T> values = EnumSet.allOf( type );
        for(T e : values) {
            if(e.getCode().equals( code )) {
                return e;
            }
        }
        throw new IllegalArgumentException( "No enum const " + type.getName() + " for code \'" + code + "\'" );
    }
    
    0 讨论(0)
提交回复
热议问题