介绍
java.lang.reflect.AnnotatedElement
public interface AnnotatedElement
getAnnotations()
和getDeclaredAnnotations()
方法返回的注解数组中,注解的顺序是不确定的Class
,Constructor
,Method
都实现了这个接口
API
- isAnnotationPresent
- 判断是否存在指定类型的注解
getAnnotation 系列:
- getAnnotation
- 返回指定类型的注解对象,如果没有则返回 null
- getAnnotations
- 返回存在的所有注解,包括从父类继承的
- getAnnotationByType
- 与 getAnnotation 类似,但如果存在多个相同类型的注解,则只返回其中一个
- 此方法与
getAnnotation(Class)
之间的区别在于,此方法检测其参数是否为可重复注释类型(@Repeatable)
getDeclaredAnnotation 系列:
- getDeclaredAnnotation
- 返回直接存在的指定类型的注解,如果没有则返回null,不考虑其继承的注解
- getDeclaredAnnotations
- 返回直接存在的所有注解,不包括继承的注解
- getDeclaredAnnotationsByType
- 与 getDeclaredAnnotations 类似,但如果存在多个相同类型的注解,则只返回其中一个
代码示例
@Inherited
如果注解上标注了 @Inherited
元注解,父类标注了该注解,那么子类也会继承该注解,通过 java.lang.Class#getAnnotations 在子类上可以获取到该注解
- AnnotatedElement 20230525 reflect java langannotatedelement 20230525 reflect java annotatedelement 20230529 reflect java 20230525 class java lang 20230525 java enum lang elementtype annotation 20230525 java retentionpolicy annotation 20230525 java annotation annotationformaterror java lang 20230528 reflect method java constructor 20230528 reflect java 20230528 reflect field java