java 反射:类和属性是否有注解

发布时间 2023-05-24 17:08:56作者: 黄光跃
  • boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
    元素上是否包含指定类型的注解,存在则返回 true,否则返回 false
  • <A extends Annotation> A getAnnotation(Class<A> annotationClass)
    获取元素上指定的注解,如果元素没有该注解返回 null
  • <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass)
    获取元素上指定的注解,如果元素没有该注解返回 null,只看元素本身,继承来的不算
  • Annotation[] getAnnotations()
    获取元素上的所有注解

自定义注解

@Target(value = {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MyAnnotation {
    String name() default "";
    int age() default 0;
    int id() default -1;
    String[] schools();
}

自己的类上使用注解

@MyAnnotation(name = "张三", age = 18, schools = {"博雅学校", "南充市第十一中学", "清华大学"})
public class Student {
}

反射获取注解

Class<Student> clazz = Student.class;

// 如果有 MyAnnotation 注解(可能是继承来的)
if (clazz.isAnnotationPresent(MyAnnotation.class)){
    // 如果是自己的注解
    MyAnnotation annotation = clazz.getDeclaredAnnotation(MyAnnotation.class);
    if (annotation != null){
        // 打印注解各项值
        System.out.println("id:" + annotation.id());
        System.out.println("name:" + annotation.name());
        System.out.println("age:" + annotation.age());
        System.out.println("schools:" + String.join(", ", annotation.schools()));
    }
}