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

  • 相关阅读:
    centos7的变化(转)
    配置邮件报警功能(脚本方式)
    临时和永久关闭Selinux
    centos7.2安装apache比较简单,直接上代码
    zabbix--------配置邮件报警功能---服务器上配置---------
    初来驾到学java修饰符的使用
    面向对象小小理解
    出来驾到学java3
    出来驾到学java2
    初来驾到学JAVA
  • 原文地址:https://www.cnblogs.com/lwmp/p/11496503.html
Copyright © 2011-2022 走看看