• Java注解demo


    # 为了熟悉了解注解,写的一个小demo
    # demo的主要功能是扫描一个class中的包含我们自定义注解的方法,然后把他们的返回值放到一个map中

    public class QQ {
    
        public static void main(String[] args)
                throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
    
            Map<String, Object> map = new HashMap<>();
    
            Class<Test> clazz = Test.class;
            Method[] mtds = clazz.getMethods();
            for (Method method : mtds) {
                // 判断方法上有没有注解
                boolean hasAnno = method.isAnnotationPresent(CacheInMap.class);
                Object result = null;
    
                // 忽略不含注解的方法
                if (!hasAnno) {
                    continue;
                }
    
                // 获取方法参数个数
                int paramCount = method.getParameterCount();
                if (paramCount == 0) {
                    result = method.invoke(clazz.newInstance());
                } else if (paramCount == 1) {
                    result = method.invoke(clazz.newInstance(), "");
                }
    
                // 获取注解
                CacheInMap anno = method.getAnnotation(CacheInMap.class);
                if ("".equals(anno.key())) {
                    String methodName = method.getName();
                    map.put(methodName, result);
                } else {
                    map.put(anno.key(), result);
                }
            }
    
            printMap(map);
        }
    
        public static void printMap(Map<String, Object> map) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                System.out.println(String.format("key:%s, value:%s", entry.getKey(), entry.getValue()));
            }
        }
    
    }
    
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
    @interface CacheInMap {
        String key() default "";
    }
    
    class Test {
    
        @CacheInMap(key = "qwer")
        public String method1(String str) {
            return "This is Method1";
        }
    
        @CacheInMap
        public int method2() {
            return 1024;
        }
    
        public double method3() {
            return 3.141592653;
        }
    }

     # 上面代码的输出结果为:

    key:method2, value:1024
    key:qwer, value:This is Method1

  • 相关阅读:
    玩转----使用数据驱动ddt时,如何写测试报告2种方法
    玩转----svn--入门
    玩转----Selenium家族简介
    起名的含义
    重新开始
    学习django: 庄园漫步
    测试常用的表格
    【Kata Daily 190927】Counting sheep...(数绵羊)
    【Kata Daily 190924】Difference of Volumes of Cuboids(长方体的体积差)
    【Kata Daily 190923】Odder Than the Rest(找出奇数)
  • 原文地址:https://www.cnblogs.com/lwmp/p/11496503.html
Copyright © 2020-2023  润新知