java反射-isAnnotationPresent()方法

定义

public interface AnnotatedElement {
    /**
     * Returns true if an annotation for the specified type
     * is present on this element, else false. This method
     * is designed primarily for convenient access to marker annotations.
     */
    default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
        return getAnnotation(annotationClass) != null;
    }
}

定义:用于检查实现此接口的类中是否存在指定类型的注解。

比如:A.isAnnotationPresent(B.class); // B类型的注解是否在A上


AnnotatedElement是个接口,如下图所示,有多个实现类。所以AccessibleObject/Class/Package类都可以调用这个方法

例子

我在开发时比较常用的是判断类上有没有注解,或类中的成员变量有没有注解,下面写下两个例子:

例子1:类上有没有注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Component {

  String value() default "";
}
@Component
public class OrderService {

  public void test() {
    System.out.println("test");
  }

}
public class Test {

  public static void main(String[] args) {
    boolean flag = OrderService.class.isAnnotationPresent(Component.class);
    System.out.println(flag);
  }

}

输出:true


例子2:类中的成员变量有没有注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Autowired {

}
@Component
public class OrderService {

  @Autowired
  private String name;
  
  public void test() {
    System.out.println("test");
  }

}
public class TestArticle {

  public static void main(String[] args) {

    for (Field field : OrderService.class.getDeclaredFields()) {
      boolean flag = field.isAnnotationPresent(Autowired.class);
      System.out.println(field.getName() + "字段是否存在Autowired.class类型的注解:" + flag);
    }
  }

}

输出:name字段是否存在Autowired.class类型的注解:true

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值