Get annotation information through reflection

Example 1

/**
* 这是自定义注解的类
*/
@Target({ ElementType.TYPE,ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyRequestMapping {
    String value(); // 这是注解的一个属性字段,也就是在使用注解时填写在括号里的参数
}
@MyRequestMapping("/test")
public class TestController {
    public void test() {
        System.out.println("进入Test方法");
    }
}
public class Test {
    public static void main(String[] args) {
        Class<?> c = TestController.class;
        MyRequestMapping baseRequestMapping = c.getAnnotation(MyRequestMapping.class);
        System.out.println(baseRequestMapping.value()); // 输出value的值
    }
}

Example 2

@Target({ ElementType.TYPE })
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Person {
    String value();
}
@MyRequestMapping("/test")
@Person("C")
public class TestController {
    public void test() {
        System.out.println("进入Test方法");
    }
}
public class Test {
    public static void main(String[] args) {
        Class<?> c = TestController.class;
        Annotation[] atnsArray = c.getAnnotations();
        for (Annotation an : atnsArray) {
            System.out.println(an);
        }
    }
}

@MyRequestMapping(value=/test) @Person(value=C)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>