java——枚举类型通过反射获取属性值并合成Map进行对比取值

枚举类型:

public enum ProfitSharing {
    /**
     * 否
     */
    NO("0", "否"),

    /**
     * 是
     */
    YES("1", "是");

    private final String code;
    private final String info;

    ProfitSharing(String code, String info) {
        this.code = code;
        this.info = info;
    }

    @Override
    public String getCode() {
        return code;
    }

    @Override
    public String getInfo() {
        return info;
    }
}

 创建泛型方法进行对比取值:

    /**
     * @param a 传入即将对比的Code值
     * @param classz 枚举类型类
     * @return
     */
    public String dictionaryTranslation(Object a,Class<?> classz){
        try{
            Map<String, String> map = new HashMap<>();
            for (Object o : classz.getEnumConstants()){
                Class<?> c = o.getClass();
                Method getCode = c.getDeclaredMethod("getCode");
                Method getInfo = c.getDeclaredMethod("getInfo");
                String code = (String) getCode.invoke(o);
                String info = (String) getInfo.invoke(o);
                System.out.println("code = " + code);
                System.out.println("info = " + info);
                map.put(code,info);
            }
            Map.Entry<String, String> stringStringEntry = map.entrySet().stream().filter(entry -> Objects.equals(entry.getKey(), String.valueOf(a))).findFirst().orElse(null);
            if (stringStringEntry != null) {
                return stringStringEntry.getValue();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

  测试类:

    @Test
    public void testClass(){
        String a = dictionaryTranslation(0,ProfitSharing.class);
        System.out.println("a= " + a);
    }

  结果:

code = 0
info = 否
code = 1
info = 是

a = 否

  

原文地址:https://www.cnblogs.com/lucky-jun/p/15319913.html