目录
AnnotationsScanner
扫描方法
扫描source为Class方法
扫描source为Method方法
辅助方法
MergedAnnotationSelector
MergedAnnotationSelectors.Nearest
MergedAnnotationSelectors.FirstDirectlyDeclared
AnnotationTypeMapping
AnnotationTypeMapping.MirrorSets
MirrorSet
MirrorSets
属性
构造过程
生成别名信息(直接AliasFor)
全层级处理别名信息
生成方便访问属性的信息
AnnotationTypeMappings
AnnotationTypeMapping帮助理解示例
注解定义
注解使用
Spring注解编程基石(一)
Spring注解编程基石(二)
Spring注解编程基石(三)
Spring注解编程基石(四)
在AnnotatedElement的注解层级中查找相关Annotation的扫描器
@Nullable
//扫描获取注解
static R scan(C context, AnnotatedElement source, SearchStrategy searchStrategy,
AnnotationsProcessor processor) {
return scan(context, source, searchStrategy, processor, null);
}
@Nullable
static R scan(C context, AnnotatedElement source, SearchStrategy searchStrategy,
AnnotationsProcessor processor, @Nullable BiPredicate> classFilter) {
R result = process(context, source, searchStrategy, processor, classFilter);
return processor.finish(result);
}
@Nullable
private static R process(C context, AnnotatedElement source,
SearchStrategy searchStrategy, AnnotationsProcessor processor,
@Nullable BiPredicate> classFilter) {
//source为类
if (source instanceof Class) {
return processClass(context, (Class>) source, searchStrategy, processor, classFilter);
}
//source为方法
if (source instanceof Method) {
return processMethod(context, (Method) source, searchStrategy, processor, classFilter);
}
return processElement(context, source, processor, classFilter);
}
@Nullable
//根据查找策略扫描Class
private static R processClass(C context, Class> source,
SearchStrategy searchStrategy, AnnotationsProcessor processor,
@Nullable BiPredicate> classFilter) {
switch (searchStrategy) {
case DIRECT:
return processElement(context, source, processor, classFilter);
case INHERITED_ANNOTATIONS:
return processClassInheritedAnnotations(context, source, searchStrategy, processor, classFilter);
case SUPERCLASS:
return processClassHierarchy(context, source, processor, classFilter, false, false);
case TYPE_HIERARCHY:
return processClassHierarchy(context, source, processor, classFilter, true, false);
case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
return processClassHierarchy(context, source, processor, classFilter, true, true);
}
throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
}
@Nullable
//查找直接注解策略
private static R processElement(C context, AnnotatedElement source,
AnnotationsProcessor processor, @Nullable BiPredicate> classFilter) {
R result = processor.doWithAggregate(context, 0);
return (result != null ? result : processor.doWithAnnotations(
context, 0, source, getDeclaredAnnotations(context, source, classFilter, false)));
}
@Nullable
//查找继承注解策略
private static R processClassInheritedAnnotations(C context, Class> source,
SearchStrategy searchStrategy, AnnotationsProcessor processor, @Nullable BiPredicate> classFilter) {
//如果没有层级,则返回查找直接注解结果
if (isWithoutHierarchy(source, searchStrategy)) {
return processElement(context, source, processor, classFilter);
}
Annotation[] relevant = null;
int remaining = Integer.MAX_VALUE;
int aggregateIndex = 0;
Class> root = source;
while (source != null && source != Object.class && remaining > 0 &&
!hasPlainJavaAnnotationsOnly(source)) {
R result = processor.doWithAggregate(context, aggregateIndex);
if (result != null) {
return result;
}
if (isFiltered(source, context, classFilter)) {
continue;
}
Annotation[] declaredAnnotations =
getDeclaredAnnotations(context, source, classFilter, true);
if (relevant == null && declaredAnnotations.length > 0) {
relevant = root.getAnnotations();
remaining = relevant.length;
}
for (int i = 0; i < declaredAnnotations.length; i++) {
if (declaredAnnotations[i] != null) {
boolean isRelevant = false;
for (int relevantIndex = 0; relevantIndex < relevant.length; relevantIndex++) {
if (relevant[relevantIndex] != null &&
declaredAnnotations[i].annotationType() == relevant[relevantIndex].annotationType()) {
isRelevant = true;
relevant[relevantIndex] = null;
remaining--;
break;
}
}
if (!isRelevant) {
declaredAnnotations[i] = null;
}
}
}
result = processor.doWithAnnotations(context, aggregateIndex, source, declaredAnnotations);
if (result != null) {
return result;
}
source = source.getSuperclass();
aggregateIndex++;
}
return null;
}
@Nullable
private static R processClassHierarchy(C context, Class> source,
AnnotationsProcessor processor, @Nullable BiPredicate> classFilter,
boolean includeInterfaces, boolean includeEnclosing) {
int[] aggregateIndex = new int[] {0};
return processClassHierarchy(context, aggregateIndex, source, processor,
classFilter, includeInterfaces, includeEnclosing);
}
@Nullable
private static R processClassHierarchy(C context, int[] aggregateIndex, Class> source,
AnnotationsProcessor processor, @Nullable BiPredicate> classFilter,
boolean includeInterfaces, boolean includeEnclosing) {
R result = processor.doWithAggregate(context, aggregateIndex[0]);
if (result != null) {
return result;
}
if (hasPlainJavaAnnotationsOnly(source)) {
return null;
}
Annotation[] annotations = getDeclaredAnnotations(context, source, classFilter, false);
result = processor.doWithAnnotations(context, aggregateIndex[0], source, annotations);
if (result != null) {
return result;
}
aggregateIndex[0]++;
if (includeInterfaces) {
for (Class> interfaceType : source.getInterfaces()) {
R interfacesResult = processClassHierarchy(context, aggregateIndex,
interfaceType, processor, classFilter, true, includeEnclosing);
if (interfacesResult != null) {
return interfacesResult;
}
}
}
Class> superclass = source.getSuperclass();
if (superclass != Object.class && superclass != null) {
R superclassResult = processClassHierarchy(context, aggregateIndex,
superclass, processor, classFilter, includeInterfaces, includeEnclosing);
if (superclassResult != null) {
return superclassResult;
}
}
Class> enclosingClass = source.getEnclosingClass();
if (includeEnclosing && enclosingClass != null) {
R enclosingResult = processClassHierarchy(context, aggregateIndex,
enclosingClass, processor, classFilter, includeInterfaces, true);
if (enclosingResult != null) {
return enclosingResult;
}
}
return null;
}
@Nullable
//根据查找策略扫描方法
private static R processMethod(C context, Method source,
SearchStrategy searchStrategy, AnnotationsProcessor processor,
@Nullable BiPredicate> classFilter) {
switch (searchStrategy) {
case DIRECT:
case INHERITED_ANNOTATIONS:
return processMethodInheritedAnnotations(context, source, processor, classFilter);
case SUPERCLASS:
return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(),
processor, classFilter, source, false);
case TYPE_HIERARCHY:
case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(),
processor, classFilter, source, true);
}
throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
}
@Nullable
private static R processMethodInheritedAnnotations(C context, Method source,
AnnotationsProcessor processor, @Nullable BiPredicate> classFilter) {
R result = processor.doWithAggregate(context, 0);
return (result != null ? result :
processMethodAnnotations(context, 0, source, processor, classFilter));
}
@Nullable
private static R processMethodHierarchy(C context, int[] aggregateIndex,
Class> sourceClass, AnnotationsProcessor processor,
@Nullable BiPredicate> classFilter, Method rootMethod,
boolean includeInterfaces) {
R result = processor.doWithAggregate(context, aggregateIndex[0]);
if (result != null) {
return result;
}
if (hasPlainJavaAnnotationsOnly(sourceClass)) {
return null;
}
boolean calledProcessor = false;
if (sourceClass == rootMethod.getDeclaringClass()) {
result = processMethodAnnotations(context, aggregateIndex[0],
rootMethod, processor, classFilter);
calledProcessor = true;
if (result != null) {
return result;
}
}
else {
for (Method candidateMethod : getBaseTypeMethods(context, sourceClass, classFilter)) {
if (candidateMethod != null && isOverride(rootMethod, candidateMethod)) {
result = processMethodAnnotations(context, aggregateIndex[0],
candidateMethod, processor, classFilter);
calledProcessor = true;
if (result != null) {
return result;
}
}
}
}
if (Modifier.isPrivate(rootMethod.getModifiers())) {
return null;
}
if (calledProcessor) {
aggregateIndex[0]++;
}
if (includeInterfaces) {
for (Class> interfaceType : sourceClass.getInterfaces()) {
R interfacesResult = processMethodHierarchy(context, aggregateIndex,
interfaceType, processor, classFilter, rootMethod, true);
if (interfacesResult != null) {
return interfacesResult;
}
}
}
Class> superclass = sourceClass.getSuperclass();
if (superclass != Object.class && superclass != null) {
R superclassResult = processMethodHierarchy(context, aggregateIndex,
superclass, processor, classFilter, rootMethod, includeInterfaces);
if (superclassResult != null) {
return superclassResult;
}
}
return null;
}
//获取基础类型方法
private static Method[] getBaseTypeMethods(
C context, Class> baseType, @Nullable BiPredicate> classFilter) {
if (baseType == Object.class || hasPlainJavaAnnotationsOnly(baseType) ||
isFiltered(baseType, context, classFilter)) {
return NO_METHODS;
}
Method[] methods = baseTypeMethodsCache.get(baseType);
if (methods == null) {
boolean isInterface = baseType.isInterface();
methods = isInterface ? baseType.getMethods() : ReflectionUtils.getDeclaredMethods(baseType);
int cleared = 0;
for (int i = 0; i < methods.length; i++) {
if ((!isInterface && Modifier.isPrivate(methods[i].getModifiers())) ||
hasPlainJavaAnnotationsOnly(methods[i]) ||
getDeclaredAnnotations(methods[i], false).length == 0) {
methods[i] = null;
cleared++;
}
}
if (cleared == methods.length) {
methods = NO_METHODS;
}
baseTypeMethodsCache.put(baseType, methods);
}
return methods;
}
方法是否覆盖
private static boolean isOverride(Method rootMethod, Method candidateMethod) {
return (!Modifier.isPrivate(candidateMethod.getModifiers()) &&
candidateMethod.getName().equals(rootMethod.getName()) &&
hasSameParameterTypes(rootMethod, candidateMethod));
}
方法是否具有相同参数类型
private static boolean hasSameParameterTypes(Method rootMethod, Method candidateMethod) {
if (candidateMethod.getParameterCount() != rootMethod.getParameterCount()) {
return false;
}
Class>[] rootParameterTypes = rootMethod.getParameterTypes();
Class>[] candidateParameterTypes = candidateMethod.getParameterTypes();
if (Arrays.equals(candidateParameterTypes, rootParameterTypes)) {
return true;
}
return hasSameGenericTypeParameters(rootMethod, candidateMethod,
rootParameterTypes);
}
方法是否具有相同泛型类型
private static boolean hasSameGenericTypeParameters(
Method rootMethod, Method candidateMethod, Class>[] rootParameterTypes) {
Class> sourceDeclaringClass = rootMethod.getDeclaringClass();
Class> candidateDeclaringClass = candidateMethod.getDeclaringClass();
if (!candidateDeclaringClass.isAssignableFrom(sourceDeclaringClass)) {
return false;
}
for (int i = 0; i < rootParameterTypes.length; i++) {
Class> resolvedParameterType = ResolvableType.forMethodParameter(
candidateMethod, i, sourceDeclaringClass).resolve();
if (rootParameterTypes[i] != resolvedParameterType) {
return false;
}
}
return true;
}
@Nullable
private static R processMethodAnnotations(C context, int aggregateIndex, Method source,
AnnotationsProcessor processor, @Nullable BiPredicate> classFilter) {
Annotation[] annotations = getDeclaredAnnotations(context, source, classFilter, false);
R result = processor.doWithAnnotations(context, aggregateIndex, source, annotations);
if (result != null) {
return result;
}
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(source);
if (bridgedMethod != source) {
Annotation[] bridgedAnnotations = getDeclaredAnnotations(context, bridgedMethod, classFilter, true);
for (int i = 0; i < bridgedAnnotations.length; i++) {
if (ObjectUtils.containsElement(annotations, bridgedAnnotations[i])) {
bridgedAnnotations[i] = null;
}
}
return processor.doWithAnnotations(context, aggregateIndex, source, bridgedAnnotations);
}
return null;
}
private static Annotation[] getDeclaredAnnotations(C context,
AnnotatedElement source, @Nullable BiPredicate> classFilter, boolean copy) {
if (source instanceof Class && isFiltered((Class>) source, context, classFilter)) {
return NO_ANNOTATIONS;
}
if (source instanceof Method && isFiltered(((Method) source).getDeclaringClass(), context, classFilter)) {
return NO_ANNOTATIONS;
}
return getDeclaredAnnotations(source, copy);
}
@SuppressWarnings("unchecked")
@Nullable
static A getDeclaredAnnotation(AnnotatedElement source, Class annotationType) {
Annotation[] annotations = getDeclaredAnnotations(source, false);
for (Annotation annotation : annotations) {
if (annotation != null && annotationType == annotation.annotationType()) {
return (A) annotation;
}
}
return null;
}
static Annotation[] getDeclaredAnnotations(AnnotatedElement source, boolean defensive) {
boolean cached = false;
Annotation[] annotations = declaredAnnotationCache.get(source);
if (annotations != null) {
cached = true;
}
else {
annotations = source.getDeclaredAnnotations();
if (annotations.length != 0) {
boolean allIgnored = true;
for (int i = 0; i < annotations.length; i++) {
Annotation annotation = annotations[i];
if (isIgnorable(annotation.annotationType()) ||
!AttributeMethods.forAnnotationType(annotation.annotationType()).isValid(annotation)) {
annotations[i] = null;
}
else {
allIgnored = false;
}
}
annotations = (allIgnored ? NO_ANNOTATIONS : annotations);
if (source instanceof Class || source instanceof Member) {
declaredAnnotationCache.put(source, annotations);
cached = true;
}
}
}
if (!defensive || annotations.length == 0 || !cached) {
return annotations;
}
return annotations.clone();
}
private static boolean isFiltered(
Class> sourceClass, C context, @Nullable BiPredicate> classFilter) {
return (classFilter != null && classFilter.test(context, sourceClass));
}
private static boolean isIgnorable(Class> annotationType) {
return AnnotationFilter.PLAIN.matches(annotationType);
}
static boolean isKnownEmpty(AnnotatedElement source, SearchStrategy searchStrategy) {
if (hasPlainJavaAnnotationsOnly(source)) {
return true;
}
if (searchStrategy == SearchStrategy.DIRECT || isWithoutHierarchy(source, searchStrategy)) {
if (source instanceof Method && ((Method) source).isBridge()) {
return false;
}
return getDeclaredAnnotations(source, false).length == 0;
}
return false;
}
static boolean hasPlainJavaAnnotationsOnly(@Nullable Object annotatedElement) {
if (annotatedElement instanceof Class) {
return hasPlainJavaAnnotationsOnly((Class>) annotatedElement);
}
else if (annotatedElement instanceof Member) {
return hasPlainJavaAnnotationsOnly(((Member) annotatedElement).getDeclaringClass());
}
else {
return false;
}
}
static boolean hasPlainJavaAnnotationsOnly(Class> type) {
return (type.getName().startsWith("java.") || type == Ordered.class);
}
private static boolean isWithoutHierarchy(AnnotatedElement source, SearchStrategy searchStrategy) {
if (source == Object.class) {
return true;
}
if (source instanceof Class) {
Class> sourceClass = (Class>) source;
boolean noSuperTypes = (sourceClass.getSuperclass() == Object.class &&
sourceClass.getInterfaces().length == 0);
return (searchStrategy == SearchStrategy.TYPE_HIERARCHY_AND_ENCLOSING_CLASSES ? noSuperTypes &&
sourceClass.getEnclosingClass() == null : noSuperTypes);
}
if (source instanceof Method) {
Method sourceMethod = (Method) source;
return (Modifier.isPrivate(sourceMethod.getModifiers()) ||
isWithoutHierarchy(sourceMethod.getDeclaringClass(), searchStrategy));
}
return true;
}
提供在2个Annotation之间进行选择的策略。
public interface MergedAnnotationSelector {
//是否最好的候选者
default boolean isBestCandidate(MergedAnnotation annotation) {
return false;
}
//选择
MergedAnnotation select(MergedAnnotation existing, MergedAnnotation candidate);
}
默认有2个实现类:
选择距离较小。
private static class Nearest implements MergedAnnotationSelector {
@Override
public boolean isBestCandidate(MergedAnnotation annotation) {
return annotation.getDistance() == 0;
}
@Override
public MergedAnnotation select(
MergedAnnotation existing, MergedAnnotation candidate) {
if (candidate.getDistance() < existing.getDistance()) {
return candidate;
}
return existing;
}
}
选择第一个直接注解的。
private static class FirstDirectlyDeclared implements MergedAnnotationSelector {
@Override
public boolean isBestCandidate(MergedAnnotation annotation) {
return annotation.getDistance() == 0;
}
@Override
public MergedAnnotation select(
MergedAnnotation existing, MergedAnnotation candidate) {
if (existing.getDistance() > 0 && candidate.getDistance() == 0) {
return candidate;
}
return existing;
}
}
提供一个注解在root注解上下文之间的映射信息。AnnotationTypeMapping的实例是由AnnotationTypeMappings创建的,创建的过程是根据注解的注释体系从下往上进行的,上层实例的source指向下层实例,所有实例的root指向最下层的实例。
MirrorSets是AnnotationTypeMapping一个内部类,是MirrorSet实例的容器。MirrorSet用于记录本注解里属性最终解析为同一个属性方法的属性信息集合,如果没有为同一个属性的别名,则不会产生MirrorSet实例,解析为同一个属性方法的一组镜像产生一个MirrorSet实例。
class MirrorSet {
//此MirrorSet被引用了多少次。
private int size;
/** 表示MirrorSet每次被引用的属性的序号。
注解镜像属性方法索引数组,size为属性方法数量。数组下标代表找到的第n-1个镜像方法,值为镜像方法的索引。
例如方法3或者4互相镜像,则0:3,1:4,后续元素值都为-1.
*/
private final int[] indexes = new int[attributes.size()];
//更新状态,根据MirrorSets.assigned
void update() {
this.size = 0;
Arrays.fill(this.indexes, -1);
for (int i = 0; i < MirrorSets.this.assigned.length; i++) {
if (MirrorSets.this.assigned[i] == this) {
this.indexes[this.size] = i;
this.size++;
}
}
}
//返回第一个不是默认值的方法的索引。
int resolve(@Nullable Object source, @Nullable A annotation,
BiFunction valueExtractor) {
int result = -1;
Object lastValue = null;
for (int i = 0; i < this.size; i++) {
Method attribute = attributes.get(this.indexes[i]);
//获取到属性的值。
Object value = valueExtractor.apply(attribute, annotation);
boolean isDefaultValue = (value == null ||
isEquivalentToDefaultValue(attribute, value, valueExtractor));
//如果属性值不是默认值,并且与上一个值不相等,则继续判断。
if (isDefaultValue || ObjectUtils.nullSafeEquals(lastValue, value)) {
continue;
}
//上一个值不为null 并且 与上一个值不相等,则抛出异常。
if (lastValue != null &&
!ObjectUtils.nullSafeEquals(lastValue, value)) {
String on = (source != null) ? " declared on " + source : "";
throw new AnnotationConfigurationException(String.format(
"Different @AliasFor mirror values for annotation [%s]%s; attribute '%s' " +
"and its alias '%s' are declared with values of [%s] and [%s].",
getAnnotationType().getName(), on,
attributes.get(result).getName(),
attribute.getName(),
ObjectUtils.nullSafeToString(lastValue),
ObjectUtils.nullSafeToString(value)));
}
//更新result,并更新lastValue。
result = this.indexes[i];
lastValue = value;
}
return result;
}
}
class MirrorSets {
private MirrorSet[] mirrorSets;
//每个属性方法引用的MirrorSet的index。未引用MirrorSet设置为-1.
private final MirrorSet[] assigned;
MirrorSets() {
//size为属性方法数量
this.assigned = new MirrorSet[attributes.size()];
this.mirrorSets = EMPTY_MIRROR_SETS;
}
/**
* 对每个mapping,此方法会调用很多次。解析的最终属性是同一个属性方法的,作为一个镜像组。
* aliases: 每个属性方法的所有层级的别名。
*/
void updateFrom(Collection aliases) {
MirrorSet mirrorSet = null;
//是别名的属性的个数
int size = 0;
//上一个别名属性的下标
int last = -1;
for (int i = 0; i < attributes.size(); i++) {
Method attribute = attributes.get(i);
//本注解定义的属性是其他属性的别名
if (aliases.contains(attribute)) {
size++;
if (size > 1) {
if (mirrorSet == null) {
mirrorSet = new MirrorSet();
this.assigned[last] = mirrorSet;
}
this.assigned[i] = mirrorSet;
}
last = i;
}
}
if (mirrorSet != null) {
mirrorSet.update();
Set unique = new LinkedHashSet<>(Arrays.asList(this.assigned));
unique.remove(null);
this.mirrorSets = unique.toArray(EMPTY_MIRROR_SETS);
}
}
int size() {
return this.mirrorSets.length;
}
MirrorSet get(int index) {
return this.mirrorSets[index];
}
@Nullable
MirrorSet getAssigned(int attributeIndex) {
return this.assigned[attributeIndex];
}
/**
* 返回本mapping每个属性最终取值的属性方法的序号 数组。
* source:注解
* annotation:注解实例
* valueExtractor:
* @return
*/
int[] resolve(@Nullable Object source, @Nullable Object annotation,
BiFunction valueExtractor) {
int[] result = new int[attributes.size()];
for (int i = 0; i < result.length; i++) {
result[i] = i;
}
for (int i = 0; i < size(); i++) {
MirrorSet mirrorSet = get(i);
//返回mirrorSet中第一个不是默认值的属性的序号。
int resolved = mirrorSet.resolve(source, annotation, valueExtractor);
//设置属性方法的最终取值的属性方法的序号。
for (int j = 0; j < mirrorSet.size; j++) {
result[mirrorSet.indexes[j]] = resolved;
}
}
return result;
}
}
final class AnnotationTypeMapping {
private static final MirrorSet[] EMPTY_MIRROR_SETS = new MirrorSet[0];
/**
*假设此AnnotationTypeMapping实例为 MA, 映射的为@A_A 注解。
*/
@Nullable
//引起此注解被解析的注解。例如:@A_A注解了@A_ROOT,则此属性指向了映射 @A_ROOT的AnnotationTypeMapping实例
private final AnnotationTypeMapping source;
//引起注解被解析的根注解。例如:@A_ROOT是解析的源头,
private final AnnotationTypeMapping root;
//离root的距离。@A_A距离@A_ROOT 为1。
private final int distance;
//此mapping对应的注解类型,此处为A_A
private final Class extends Annotation> annotationType;
//涉及到的注解类型列表。包括source的metaTypes 加上 annotationType
private final List> metaTypes;
@Nullable
//注解类型实例。
private final Annotation annotation;
//注解的属性方法列表包装类。
private final AttributeMethods attributes;
/**
*MirrorSet集合
*本注解里声明的属性,最终为同一个属性的 别名 的属性集合为一个MirrorSet
*/
private final MirrorSets mirrorSets;
//每个属性在root中对应的同名的属性方法的索引。与conventionMappings 的区别是,它是同名的属性,不考虑别名。
private final int[] aliasMappings;
/**方便访问属性 的映射消息,如果在root中有别名,则优先获取,
*/
private final int[] conventionMappings;
//与annotationValueSource是相匹配的,定义每个属性最终从哪个注解的哪个属性获取值。
private final int[] annotationValueMappings;
private final AnnotationTypeMapping[] annotationValueSource;
//存储每个属性的所有别名属性方法(仅限于本注解定义中的属性方法),
// Key:AliasFor里定义的属性方法,value为本注解内声明的属性方法。resolveAliasedForTargets方法中解析
private final Map> aliasedBy;
//本注解声明的所有属性方法的所有别名集合。最后用于注解定义检查然后会清空
private final Set claimedAliases = new HashSet<>();
}
AnnotationTypeMapping(@Nullable AnnotationTypeMapping source,
Class extends Annotation> annotationType, @Nullable Annotation annotation) {
this.source = source;
this.root = (source != null ? source.getRoot() : this);
this.distance = (source == null ? 0 : source.getDistance() + 1);
this.annotationType = annotationType;
this.metaTypes = merge(
source != null ? source.getMetaTypes() : null,
annotationType);
this.annotation = annotation;
this.attributes = AttributeMethods.forAnnotationType(annotationType);
this.mirrorSets = new MirrorSets();
this.aliasMappings = filledIntArray(this.attributes.size());
this.conventionMappings = filledIntArray(this.attributes.size());
this.annotationValueMappings = filledIntArray(this.attributes.size());
this.annotationValueSource = new AnnotationTypeMapping[this.attributes.size()];
//返回每个属性方法的所有别名(本注解声明的属性方法)。
this.aliasedBy = resolveAliasedForTargets();
processAliases();
addConventionMappings();
addConventionAnnotationValues();
}
//返回每个属性方法的所有别名(本注解声明的属性方法)。
//Key:AliasFor里定义的属性方法,value为本注解内声明的属性方法。
private Map> resolveAliasedForTargets() {
Map> aliasedBy = new HashMap<>();
for (int i = 0; i < this.attributes.size(); i++) {
//声明的属性方法(作为value集合元素)。
Method attribute = this.attributes.get(i);
AliasFor aliasFor = AnnotationsScanner.getDeclaredAnnotation(attribute, AliasFor.class);
if (aliasFor != null) {
//最终解析的属性方法(作为key)。
Method target = resolveAliasTarget(attribute, aliasFor);
aliasedBy.computeIfAbsent(target, key -> new ArrayList<>()).add(attribute);
}
}
return Collections.unmodifiableMap(aliasedBy);
}
//解析属性方法AliasFor的Method。
private Method resolveAliasTarget(Method attribute, AliasFor aliasFor, boolean checkAliasPair) {
if (StringUtils.hasText(aliasFor.value()) && StringUtils.hasText(aliasFor.attribute())) {
throw new AnnotationConfigurationException(String.format(
"In @AliasFor declared on %s, attribute 'attribute' and its alias 'value' " +
"are present with values of '%s' and '%s', but only one is permitted.",
AttributeMethods.describe(attribute), aliasFor.attribute(),
aliasFor.value()));
}
aliased注解。
Class extends Annotation> targetAnnotation = aliasFor.annotation();
//如果没有设置annotation属性,则表示是在本注解定义内。
if (targetAnnotation == Annotation.class) {
targetAnnotation = this.annotationType;
}
// aliased注解的属性。通过AliasFor的attribute或者value属性获取,
String targetAttributeName = aliasFor.attribute();
if (!StringUtils.hasLength(targetAttributeName)) {
targetAttributeName = aliasFor.value();
}
//如果attribute或者value都没有值,则获取aliased注解的属性方法名称。
if (!StringUtils.hasLength(targetAttributeName)) {
targetAttributeName = attribute.getName();
}
//获取最终的aliased注解的属性方法。
Method target = AttributeMethods.forAnnotationType(targetAnnotation).get(targetAttributeName);
........... 此处省略校验逻辑
return target;
}
//处理别名,生成MirrorSets,
private void processAliases() {
List aliases = new ArrayList<>();
for (int i = 0; i < this.attributes.size(); i++) {
aliases.clear();
//本属性方法的所有别名先加入。
aliases.add(this.attributes.get(i));
//再递归收集别名的别名,.......
collectAliases(aliases);
if (aliases.size() > 1) {
processAliases(i, aliases);
}
}
}
//递归AnnotationTypeMapping链,收集别名(最终解析到此属性方法的所有别名)。
private void collectAliases(List aliases) {
AnnotationTypeMapping mapping = this;
while (mapping != null) {
int size = aliases.size();
for (int j = 0; j < size; j++) {
List additional = mapping.aliasedBy.get(aliases.get(j));
if (additional != null) {
aliases.addAll(additional);
}
}
mapping = mapping.source;
}
}
/**
* 对每个属性方法,处理它的别名。
* aliases:每个属性方法的所有层级的别名。
*/
private void processAliases(int attributeIndex, List aliases) {
//获取root声明的第一个别名属性的index。-1表示root不存在此属性方法的别名。
int rootAttributeIndex = getFirstRootAttributeIndex(aliases);
AnnotationTypeMapping mapping = this;
while (mapping != null) {
//在root中有别名,并且此mapping不是root
if (rootAttributeIndex != -1 && mapping != this.root) {
for (int i = 0; i < mapping.attributes.size(); i++) {
//如果别名中有此属性,则对应的属性index值为root的属性的index。
if (aliases.contains(mapping.attributes.get(i))) {
mapping.aliasMappings[i] = rootAttributeIndex;
}
}
}
//更新mapping的mirrorSets。
mapping.mirrorSets.updateFrom(aliases);
//mapping声明的属性方法的别名集合。
mapping.claimedAliases.addAll(aliases);
if (mapping.annotation != null) {
//返回本mapping每个属性最终取值的属性方法的序号 数组。
int[] resolvedMirrors = mapping.mirrorSets.resolve(null,
mapping.annotation, ReflectionUtils::invokeMethod);
for (int i = 0; i < mapping.attributes.size(); i++) {
//本属性方法是别名,则设置注解值的最终来源(mppaing和属性序号)
if (aliases.contains(mapping.attributes.get(i))) {
this.annotationValueMappings[attributeIndex] = resolvedMirrors[i];
this.annotationValueSource[attributeIndex] = mapping;
}
}
}
mapping = mapping.source;
}
}
//生成从root访问属性的方便属性方法信息
private void addConventionMappings() {
if (this.distance == 0) {
return;
}
AttributeMethods rootAttributes = this.root.getAttributes();
//此时,元素值全为-1.
int[] mappings = this.conventionMappings;
for (int i = 0; i < mappings.length; i++) {
String name = this.attributes.get(i).getName();
MirrorSet mirrors = getMirrorSets().getAssigned(i);
//root中是否存在同名的属性
int mapped = rootAttributes.indexOf(name);
//root中存在同名的属性,并且属性名不为value
if (!MergedAnnotation.VALUE.equals(name) && mapped != -1) {
//存储root中的属性方法index。
mappings[i] = mapped;
if (mirrors != null) {
for (int j = 0; j < mirrors.size(); j++) {
//同一属性的所有别名,设置成一样的root 属性index。
mappings[mirrors.getAttributeIndex(j)] = mapped;
}
}
}
}
}
//是更好的注解值获取属性方法(Value属性优先,distance较小的优先)
private boolean isBetterConventionAnnotationValue(int index, boolean isValueAttribute,
AnnotationTypeMapping mapping) {
//原来没有获取值的属性方法。
if (this.annotationValueMappings[index] == -1) {
return true;
}
int existingDistance = this.annotationValueSource[index].distance;
return !isValueAttribute && existingDistance > mapping.distance;
}
//更新各级AnnotationTypeMapping的annotationValueMappings和annotationValueSource
private void addConventionAnnotationValues() {
for (int i = 0; i < this.attributes.size(); i++) {
Method attribute = this.attributes.get(i);
boolean isValueAttribute = MergedAnnotation.VALUE.equals(attribute.getName());
AnnotationTypeMapping mapping = this;
//在向root端(mapping.distance 比自己下的)遍历。
while (mapping != null && mapping.distance > 0) {
int mapped = mapping.getAttributes().indexOf(attribute.getName());
//有同名属性
if (mapped != -1 && isBetterConventionAnnotationValue(i, isValueAttribute, mapping)) {
this.annotationValueMappings[i] = mapped;
this.annotationValueSource[i] = mapping;
}
mapping = mapping.source;
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@interface A_C
{
@AliasFor(value = "c2")
String c1() default "A_C_1";
@AliasFor(value = "c1")
String c2() default "A_C_1";
String c3() default "A_C_3";
@AliasFor(value = "c5")
String c4() default "A_C_4";
@AliasFor(value = "c4")
String c5() default "A_C_4";
String c6() default "A_C_6";
}
@A_C
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@interface A_B
{
@AliasFor(value = "c2",annotation = A_C.class)
String b1() default "A_B_1_2";
@AliasFor(value = "c2",annotation = A_C.class)
String b2() default "A_B_1_2";
@AliasFor(value = "c2",annotation = A_C.class)
String b3() default "A_B_1_2";
String b4() default "A_B_4";
}
@A_B
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@interface A_A
{
@AliasFor(value = "c1",annotation = A_C.class)
String a1() default "A_A_1";
String a2() default "A_A_2";
}
@A_A
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@interface A_ROOT
{
}
@A_ROOT
public class AnnotationUtilTest {
public static void main(String[] args) {
AnnotationAttributes a =AnnotatedElementUtils.findMergedAnnotationAttributes(AnnotationUtilTest.class,A_A.class,false,true);
AnnotationAttributes b =AnnotatedElementUtils.findMergedAnnotationAttributes(AnnotationUtilTest.class,A_B.class,false,true);
AnnotationAttributes c =AnnotatedElementUtils.findMergedAnnotationAttributes(AnnotationUtilTest.class,A_C.class,false,true);
AnnotationAttributes root =AnnotatedElementUtils.findMergedAnnotationAttributes(AnnotationUtilTest.class,A_ROOT.class,false,true);
System.out.println("x");
}
}
@A_ROOT
public class AnnotationUtilTest {
public static void main(String[] args) {
AnnotationAttributes a =AnnotatedElementUtils.findMergedAnnotationAttributes(AnnotationUtilTest.class,A_A.class,false,true);
AnnotationAttributes b =AnnotatedElementUtils.findMergedAnnotationAttributes(AnnotationUtilTest.class,A_B.class,false,true);
AnnotationAttributes c =AnnotatedElementUtils.findMergedAnnotationAttributes(AnnotationUtilTest.class,A_C.class,false,true);
AnnotationAttributes root =AnnotatedElementUtils.findMergedAnnotationAttributes(AnnotationUtilTest.class,A_ROOT.class,false,true);
System.out.println("x");
}
}
返回的AnnotationTypeMappings实例属性
获取到AnnotationTypeMappings后,循环处理与requiredType相关的AnnotationTypeMapping ,获取到MergedAnnotation,选择一个最合适的MergedAnnotation
AnnotationTypeMappings mappings = AnnotationTypeMappings.forAnnotationType(
annotation.annotationType(), annotationFilter);
for (int i = 0; i < mappings.size(); i++) {
AnnotationTypeMapping mapping = mappings.get(i);
if (isMappingForType(mapping, annotationFilter, this.requiredType)) {
MergedAnnotation candidate = TypeMappedAnnotation.createIfPossible(
mapping, source, annotation, aggregateIndex, IntrospectionFailureLogger.INFO);
if (candidate != null && (this.predicate == null || this.predicate.test(candidate))) {
if (this.selector.isBestCandidate(candidate)) {
return candidate;
}
updateLastResult(candidate);
}
}
}
private static boolean isMappingForType(AnnotationTypeMapping mapping,
AnnotationFilter annotationFilter, @Nullable Object requiredType) {
Class extends Annotation> actualType = mapping.getAnnotationType();
//未过滤掉并且(requiredType 为空 或者是同一个类型,或者名称相同)
return (!annotationFilter.matches(actualType) &&
(requiredType == null || actualType == requiredType || actualType.getName().equals(requiredType)));
}