zoukankan      html  css  js  c++  java
  • 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 = 否
    

      

  • 相关阅读:
    hdu 1698
    ACM起步要点总结(转哈工大)
    RANSAC
    Android 颜色渲染(十) ComposeShader组合渲染
    java过滤html标签函数
    Objective-C ,ios,iphone开发基础:picker控件详解与使用,(实现省市的二级联动)
    简单的三方登录SDK示例,Android Activity之间数据的传递
    搜索引擎日志分析
    继续过中等难度的题目
    包圈圈的题目
  • 原文地址:https://www.cnblogs.com/lucky-jun/p/15319913.html
Copyright © 2011-2022 走看看