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

转载于:https://www.cnblogs.com/lwmp/p/11496503.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值