public class SyntheticAnnotation<A extends Annotation> extends Object implements Annotation, AnnotatedElement
假设现有注解A,A上存在元注解B,B上存在元注解C,则对A解析得到的合成注解X,则CBA都是X的元注解,X为根注解。
通过AnnotatedElement.isAnnotationPresent(Class)可确定指定类型是注解是否是该合成注解的元注解,即是否为当前实例的“父类”。
若指定注解是当前实例的元注解,则通过getAnnotation(Class)可获得动态代理生成的对应的注解实例。
需要注意的是,由于认为合并注解X以最初的根注解A作为元注解,因此getAnnotations()或getDeclaredAnnotations()
都将只能获得A。
不同层级的元注解可能存在同名的属性,此时,若认为该合成注解X在第0层,则根注解A在第1层,B在第2层......以此类推。
层级越低的注解中离根注解距离近,则属性优先级越高,即遵循“就近原则”。
举个例子:若CBA同时存在属性y,则将X视为C,B或者A时,获得的y属性的值都与最底层元注解A的值保持一致。
同理,不同层级可能会出现相同的元注解,比如A注解存在元注解B,C,但是C又存在元注解B,因此根据就近原则,A上的元注解B将优先于C上的元注解B生效。
若两相同注解处于同一层级,则按照从其上一级“子注解”的AnnotatedElement.getAnnotations()的调用顺序排序。
getAnnotation(Class)获得的代理类实例的属性值遵循该规则。
同名属性将根据类型彼此隔离,即当不同层级的元注解存在同名的属性,但是属性类型不同时,此时低层级的属性并不会覆盖高层级注解的属性。
别名在合成注解中仍然有效,若注解X中任意属性上存在Alias注解,则Alias.value()指定的属性值将会覆盖注解属性的本身的值。
Alias注解仅能指定注解X中存在的属性作为别名,不允许指定元注解或子类注解的属性。
AnnotationUtil| 限定符和类型 | 方法和说明 |
|---|---|
Class<? extends Annotation> |
annotationType()
获取根注解类型
|
<T extends Annotation> |
getAnnotation(Class<T> annotationType)
若合成注解在存在指定元注解,则使用动态代理生成一个对应的注解实例
|
Annotation[] |
getAnnotations()
获取全部注解
|
Object |
getAttribute(String attributeName,
Class<?> attributeType)
根据指定的属性名与属性类型获取对应的属性值,若存在
Alias则获取Alias.value()指定的别名属性的值
当不同层级的注解之间存在同名同类型属性时,将优先获取更接近根注解的属性 |
Annotation[] |
getDeclaredAnnotations()
获取根注解直接声明的注解,该方法正常情况下当只返回原注解
|
A |
getSource()
获取根注解
|
static <T extends Annotation> |
of(T rootAnnotation)
基于指定根注解,构建包括其元注解在内的合成注解
|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitequals, hashCode, toStringgetAnnotationsByType, getDeclaredAnnotation, getDeclaredAnnotationsByType, isAnnotationPresentpublic static <T extends Annotation> SyntheticAnnotation<T> of(T rootAnnotation)
T - 注解类型rootAnnotation - 根注解public A getSource()
public Class<? extends Annotation> annotationType()
annotationType 在接口中 Annotationpublic Object getAttribute(String attributeName, Class<?> attributeType)
attributeName - 属性名attributeType - 属性类型public <T extends Annotation> T getAnnotation(Class<T> annotationType)
getAnnotation 在接口中 AnnotatedElementT - 注解类型annotationType - 注解类型public Annotation[] getAnnotations()
getAnnotations 在接口中 AnnotatedElementpublic Annotation[] getDeclaredAnnotations()
getDeclaredAnnotations 在接口中 AnnotatedElementCopyright © 2022. All rights reserved.