定义
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