zoukankan      html  css  js  c++  java
  • 通过反射获取注解

    自定义注解

    /**
     * 日志注解
     */
    
    @Target({ElementType.METHOD,ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Log {
        String value() default "";
    }
    
    

    使用注解的类

    @Component
    @Log("小明呀")
    public class TargetclassTest {
    
        @Log("小明")
        public void getMoney(String name, String money) {
    //        int i = 1/0;
            System.out.println(name + "有" + money + "元");
        }
    }
    

    获取方法上的注解

        /**
         * 通过反射获取方法上的注解
         */
        @Test
        public void reflectionAnnotationMethod() throws NoSuchMethodException {
            Class clazz = TargetclassTest.class;
            Method getMoney = clazz.getDeclaredMethod("getMoney", String.class, String.class);
            if (getMoney.isAnnotationPresent(Log.class)) {
                Log declaredAnnotation = getMoney.getDeclaredAnnotation(Log.class);
                System.out.println(declaredAnnotation.value());
            }
        }
    

    获取类上的注解

        /**
         * 通过反射获取类上的注解
         */
        @Test
        public void reflectionAnnotationClass() throws NoSuchMethodException {
            Class clazz = TargetclassTest.class;
            if (clazz.isAnnotationPresent(Log.class)) {
                Log declaredAnnotation = (Log) clazz.getDeclaredAnnotation(Log.class);
                System.out.println(declaredAnnotation.value());
            }
        }
    
  • 相关阅读:
    rsync特性
    01 什么是爬虫
    celery的使用
    redis的使用
    GIT使用大全
    多项式的高级运算
    SP1557 GSS2
    题解 CF997E 【Good Subsegments】
    P3920 [WC2014]紫荆花之恋
    题解 P3750 【[六省联考2017]分手是祝愿】
  • 原文地址:https://www.cnblogs.com/PoetryAndYou/p/14557376.html
Copyright © 2011-2022 走看看