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 = 否
    

      

  • 相关阅读:
    预搜索,不匹配;反向预搜索,不匹配
    反向引用 /1, /2...
    贪婪与非贪婪模式
    其他一些代表抽象意义的特殊符号
    修饰匹配次数的特殊符号
    自定义能够匹配 ' 多种字符' 的表达式
    能够与 ' 多种字符' 匹配的表达式
    6)添加带有颜色的那个画板
    5)添加快捷键
    4)记住我的图形
  • 原文地址:https://www.cnblogs.com/lucky-jun/p/15319913.html
Copyright © 2011-2022 走看看