一 Metadata 元数据封装
Metadata 对象用于对类进行封装,其拥有 4 接口及 3 个实现类,其中 StandardClassMetadata 与 StandardAnnotationMetadata 类用于封装普通非注解类,SimpleMetadataReader 类则用于封装注解类及用于封装方法的 SimpleMethodMetadata 与 StandardMethodMetadata 类;
1 接口
1.1 ClassMetadata 接口
ClassMetadata 接口向外提供了获取类基本信息的功能,其中 getClassName、getSuperClassName、getEnclosingClassName、getInterfaceNames 及 getMemberClassNames 方法用于获取相关类名;isInterface、isAnnotation、isAbstract、isConcrete、isFinal 与 isIndependent 方法则用于判断类的某种类型;hasEnclosingClass 与 hasSuperClass 方法分别用于判断类中是否拥有内部类或父类。
public interface ClassMetadata {
String getClassName();
boolean isInterface();
boolean isAnnotation();
boolean isAbstract();
default boolean isConcrete() {
return !(isInterface() || isAbstract());
}
boolean isFinal();
boolean isIndependent();
default boolean hasEnclosingClass() {
return (getEnclosingClassName() != null);
}
@Nullable
String getEnclosingClassName();
default boolean hasSuperClass() {
return (getSuperClassName() != null);
}
@Nullable
String getSuperClassName();
String[] getInterfaceNames();
String[] getMemberClassNames();
}
1.2 AnnotatedTypeMetadata 接口
AnnotatedTypeMetadata 接口向外提供获取使用注解修饰的类相关操作方法;其只有一个用于获取所有修饰类元数据注解对象的 getAnnotations 方法是抽象方法;其他所有方法都是 default 方法且都是基于 getAnnotations 方法,isAnnotated 方法判断当前类是否拥有指定名字的注解、getAnnotationAttributes 与 getAllAnnotationAttributes 方法则是用于获取指定属性的所有参数键值对Map。
public interface AnnotatedTypeMetadata {
MergedAnnotations getAnnotations();
default boolean isAnnotated(String annotationName) {
return getAnnotations().isPresent(annotationName);
}
@Nullable
default Map<String, Object> getAnnotationAttributes(String annotationName) {
return getAnnotationAttributes(annotationName, false);
}
@Nullable
default Map<String, Object> getAnnotationAttributes(String annotationName,
boolean classValuesAsString) {
MergedAnnotation<Annotation> annotation = getAnnotations().get(annotationName,
null, MergedAnnotationSelectors.firstDirectlyDeclared());
if (!annotation.isPresent()) {
return null;
}
return annotation.asAnnotationAttributes(Adapt.values(classValuesAsString, true));
}
@Nullable
default MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationName) {
return getAllAnnotationAttributes(annotationName, false);
}
@Nullable
default MultiValueMap<String, Object> getAllAnnotationAttributes(
String annotationName, boolean classValuesAsString) {
Adapt[] adaptations = Adapt.values(classValuesAsString, true);
return getAnnotations().stream(annotationName)
.filter(MergedAnnotationPredicates.unique(MergedAnnotation::getMetaTypes))
.map(MergedAnnotation::withNonMergedAttributes)
.collect(MergedAnnotationCollectors.toMultiValueMap(map ->
map.isEmpty() ? null : map, adaptations));
}
}
1.3 AnnotationMetadata 接口
AnnotationMetadata 接口则扩展了向外提供对元数据所有注解进行操作的相关功能;其中 getAnnotationTypes、getMetaAnnotationTypes 及 getAnnotatedMethods 方法分别用于获取类的直接注解名集合、指定注解的元注解名集合及拥有指定名注解的方法元数据集合;hasAnnotation、hasMetaAnnotation 与 hasAnnotatedMethods 方法则分别用于获取元数据类是否拥有指定注解、是否拥有指定名的元注解与使用拥有使用指定名注解修饰的方法;除了上述方法之外,其还有一个使用指定类对象创建 StandardAnnotationMetadata 对象的 introspect 静态方法。
public interface AnnotationMetadata extends ClassMetadata, AnnotatedTypeMetadata {
default Set<String> getAnnotationTypes() {
return getAnnotations().stream()
.filter(MergedAnnotation::isDirectlyPresent)
.map(annotation -> annotation.getType().getName())
.collect(Collectors.toCollection(LinkedHashSet::new));
}
default Set<String> getMetaAnnotationTypes(String annotationName) {
MergedAnnotation<?> annotation = getAnnotations().get(annotationName, MergedAnnotation::isDirectlyPresent);
if (!annotation.isPresent()) {
return Collections.emptySet();
}
return MergedAnnotations.from(annotation.getType(), SearchStrategy.INHERITED_ANNOTATIONS).stream()
.map(mergedAnnotation -> mergedAnnotation.getType().getName())
.collect(Collectors.toCollection(LinkedHashSet::new));
}
default boolean hasAnnotation(String annotationName) {
return getAnnotations().isDirectlyPresent(annotationName);
}
default boolean hasMetaAnnotation(String metaAnnotationName) {
return getAnnotations().get(metaAnnotationName,
MergedAnnotation::isMetaPresent).isPresent();
}
default boolean hasAnnotatedMethods(String annotationName) {
return !getAnnotatedMethods(annotationName).isEmpty();
}
Set<MethodMetadata> getAnnotatedMethods(String annotationName);
static AnnotationMetadata introspect(Class<?> type) {
return StandardAnnotationMetadata.from(type);
}
}
2 StandardClassMetadata 类
2.1 属性与构造方法
StandardClassMetadata 类只有一个类属性变量与构造方法,其用于非注解类的封装;introspectedClass 属性用于保存其封装内部类对象,其构造方法已经过时,从其注解可以看出使用该类的地方全使用 StandardAnnotationMetadata 类进行替换。
public class StandardClassMetadata implements ClassMetadata {
private final Class<?> introspectedClass;
@Deprecated
public StandardClassMetadata(Class<?> introspectedClass) {
Assert.notNull(introspectedClass, "Class must not be null");
this.introspectedClass = introspectedClass;
}
public final Class<?> getIntrospectedClass() {
return this.introspectedClass;
}
}
2.2 其余方法
StandardClassMetadata 类中的 getClassName、isInterface 与 isAnnotation 方法直接调用 introspectedClass;isAbstract 与 isFinal 方法则是使用 introspectedClass 的 getModifiers 方法对其进行判断;isIndependent 方法在 hasEnclosingClass 方法为 false 时直接返回 true,否则返回 introspectedClass 的 getDeclaringClass 结果不为空且 introspectedClass 是否为静态类执行结果;getEnclosingClassName 方法则是在 introspectedClass 属性在其拥有外部类时直接获取其外部类名;getSuperClassName 方法则是在 introspectedClass 属性拥有父类时直接返回其名否则返回 null;getInterfaceNames 方法则是对 introspectedClass 所有实现接口进行遍历并返回其名字符串数组;getMemberClassNames 则是返回 introspectedClass 属性中的所有内部类包含所有限定符修饰的接口与抽象类;
public class StandardClassMetadata implements ClassMetadata {
@Override
public String getClassName() {
return this.introspectedClass.getName();
}
@Override
public boolean isInterface() {
return this.introspectedClass.isInterface();
}
@Override
public boolean isAnnotation() {
return this.introspectedClass.isAnnotation();
}
@Override
public boolean isAbstract() {
return Modifier.isAbstract(this.introspectedClass.getModifiers());
}
@Override
public boolean isFinal() {
return Modifier.isFinal(this.introspectedClass.getModifiers());
}
@Override
public boolean isIndependent() {
return (!hasEnclosingClass() ||
(this.introspectedClass.getDeclaringClass() != null &&
Modifier.isStatic(this.introspectedClass.getModifiers())));
}
@Override
@Nullable
public String getEnclosingClassName() {
Class<?> enclosingClass = this.introspectedClass.getEnclosingClass();
return (enclosingClass != null ? enclosingClass.getName() : null);
}
@Override
@Nullable
public String getSuperClassName() {
Class<?> superClass = this.introspectedClass.getSuperclass();
return (superClass != null ? superClass.getName() : null);
}
@Override
public String[] getInterfaceNames() {
Class<?>[] ifcs = this.introspectedClass.getInterfaces();
String[] ifcNames = new String[ifcs.length];
for (int i = 0; i < ifcs.length; i++) {
ifcNames[i] = ifcs[i].getName();
}
return ifcNames;
}
@Override
public String[] getMemberClassNames() {
LinkedHashSet<String> memberClassNames = new LinkedHashSet<>(4);
for (Class<?> nestedClass : this.introspectedClass.getDeclaredClasses()) {
memberClassNames.add(nestedClass.getName());
}
return StringUtils.toStringArray(memberClassNames);
}
}
3 StandardAnnotationMetadata 类
3.1 属性与构造方法
3.1.1 属性变量
StandardAnnotationMetadata 类扩展了获取类相关注解属性相关功能,其拥有三个类属性变量:用于保存内部类中所有使用的注解的 mergedAnnotations 属性,用于标识在获取注解属性时是否级联返回父类的注解属性值的 nestedAnnotationsAsMap 标识以及用于保存当前类的所有直接注解类型名。
public class StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata {
private final MergedAnnotations mergedAnnotations;
private final boolean nestedAnnotationsAsMap;
@Nullable
private Set<String> annotationTypes;
@Override
public MergedAnnotations getAnnotations() {
return this.mergedAnnotations;
}
}
3.1.2 构造方法
StandardAnnotationMetadata 类拥有两个构造方法,其在 nestedAnnotationsAsMap 属性未传入时直接使用 false,在对象的创建过程中首先调用父类构造方法为 introspectedClass 内部类属性进行初始化并将 mergedAnnotations 属性值初始化为 MergedAnnotations 的 from 方法结果值,最后将 nestedAnnotationsAsMap 属性值初始化为对应参数值。
public class StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata {
@Deprecated
public StandardAnnotationMetadata(Class<?> introspectedClass) {
this(introspectedClass, false);
}
@Deprecated
public StandardAnnotationMetadata(Class<?> introspectedClass, boolean nestedAnnotationsAsMap) {
super(introspectedClass);
this.mergedAnnotations = MergedAnnotations.from(introspectedClass,
SearchStrategy.INHERITED_ANNOTATIONS, RepeatableContainers.none());
this.nestedAnnotationsAsMap = nestedAnnotationsAsMap;
}
}
3.2 AnnotationMetadata 接口实现
3.2.1 getAnnotationTypes 方法
getAnnotationTypes 方法在 annotationTypes 属性为空时,将其初始化为 AnnotationMetadata 接口的 getAnnotationTypes 方法结果值,同时返回 annotationTypes 属性值;
public class StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata {
@Override
public Set<String> getAnnotationTypes() {
Set<String> annotationTypes = this.annotationTypes;
if (annotationTypes == null) {
annotationTypes = Collections.unmodifiableSet(AnnotationMetadata.super.getAnnotationTypes());
this.annotationTypes = annotationTypes;
}
return annotationTypes;
}
}
3.2.2 getAnnotationAttributes 方法
getAnnotationAttributes 方法在 nestedAnnotationsAsMap 属性为 true 时直接返回 AnnotationMetadata 接口的 getAnnotationAttributes 方法结果值,否则返回 AnnotatedElementUtils 类的 getMergedAnnotationAttributes 静态方法结果值;
public class StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata {
@Override
@Nullable
public Map<String, Object> getAnnotationAttributes(String annotationName, boolean classValuesAsString) {
if (this.nestedAnnotationsAsMap) {
return AnnotationMetadata.super.getAnnotationAttributes(annotationName, classValuesAsString);
}
return AnnotatedElementUtils.getMergedAnnotationAttributes(
getIntrospectedClass(), annotationName, classValuesAsString, false);
}
}
3.2.3 getAllAnnotationAttributes 方法
getAllAnnotationAttributes 方法在 nestedAnnotationsAsMap 属性为 true 时直接返回 AnnotationMetadata 接口的 getAllAnnotationAttributes 方法结果值,否则返回 AnnotatedElementUtils 类的 getAllAnnotationAttributes 静态方法结果值;
public class StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata {
@Override
@Nullable
public MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationName, boolean classValuesAsString) {
if (this.nestedAnnotationsAsMap) {
return AnnotationMetadata.super.getAllAnnotationAttributes(annotationName, classValuesAsString);
}
return AnnotatedElementUtils.getAllAnnotationAttributes(
getIntrospectedClass(), annotationName, classValuesAsString, false);
}
}
3.2.4 hasAnnotatedMethods 方法
hasAnnotatedMethods 方法在内部类中没有使用名为 annotationName 的注解修饰的内容(包含属性、方法及内部类等)时直接返回 false,否则对内部类中的所有方法对象进行遍历,使用 isAnnotatedMethod 方法判断其中是否存在名为 annotationName 的注解修饰的方法,一旦发现了该方法对象时直接返回 true;
public class StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata {
@Override
public boolean hasAnnotatedMethods(String annotationName) {
if (AnnotationUtils.isCandidateClass(getIntrospectedClass(), annotationName)) {
try {
Method[] methods = ReflectionUtils.getDeclaredMethods(getIntrospectedClass());
for (Method method : methods) {
if (isAnnotatedMethod(method, annotationName)) {
return true;
}
}
}
catch (Throwable ex) {
throw new IllegalStateException("Failed to introspect annotated methods on " + getIntrospectedClass(), ex);
}
}
return false;
}
private boolean isAnnotatedMethod(Method method, String annotationName) {
return !method.isBridge() && method.getAnnotations().length > 0 &&
AnnotatedElementUtils.isAnnotated(method, annotationName);
}
}
3.2.4 getAnnotatedMethods 方法
getAnnotatedMethods 方法在内部类中没有使用名为 annotationName 的注解修饰的内容(包含属性、方法及内部类等)时直接返回 null,否则对内部类中的所有方法对象进行遍历,将其中 isAnnotatedMethod 方法判断当前方法是否使用名为 annotationName 的注解修饰的方法进行修饰,满足时则使用该方法对象与 nestedAnnotationsAsMap 属性创建 StandardMethodMetadata 对象并将其添加到 annotatedMethods 局部参数中;随后在完成方法对象遍历后直接返回 annotatedMethods 变量值。
public class StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata {
@Override
@SuppressWarnings("deprecation")
public Set<MethodMetadata> getAnnotatedMethods(String annotationName) {
Set<MethodMetadata> annotatedMethods = null;
if (AnnotationUtils.isCandidateClass(getIntrospectedClass(), annotationName)) {
try {
Method[] methods = ReflectionUtils.getDeclaredMethods(getIntrospectedClass());
for (Method method : methods) {
if (isAnnotatedMethod(method, annotationName)) {
if (annotatedMethods == null) {
annotatedMethods = new LinkedHashSet<>(4);
}
annotatedMethods.add(new StandardMethodMetadata(method, this.nestedAnnotationsAsMap));
}
}
}
catch (Throwable ex) {
throw new IllegalStateException("Failed to introspect annotated methods on " + getIntrospectedClass(), ex);
}
}
return annotatedMethods != null ? annotatedMethods : Collections.emptySet();
}
}
3.3 from 方法
from 方法直接使用 introspectedClass 参数与 true 值创建 StandardAnnotationMetadata 对象并返回。
public class StandardAnnotationMetadata extends StandardClassMetadata implements AnnotationMetadata {
static AnnotationMetadata from(Class<?> introspectedClass) {
return new StandardAnnotationMetadata(introspectedClass, true);
}
}
4 StandardAnnotationMetadata 类
4.1 属性与构造方法
4.1.1 属性变量
SimpleAnnotationMetadata 类简单的封装类,其中 className 、 enclosingClassName 与 superClassName 属性分别保存封装类名、外部类名与父类名,access 属性则保存类标识二进制位图,independentInnerClass 属性则是封装类是否为非静态内部类,interfaceNames 与 memberClassNames 属性分别保存的则是封装类实现的接口名与其内部类名数组,annotatedMethods 属性存储所有注解封装对象数组,annotations 保存的当前使用的注解封装对象及保存注解类型名 set 集合的 annotationTypes 属性;
final class SimpleAnnotationMetadata implements AnnotationMetadata {
private final String className;
private final int access;
@Nullable
private final String enclosingClassName;
@Nullable
private final String superClassName;
private final boolean independentInnerClass;
private final String[] interfaceNames;
private final String[] memberClassNames;
private final MethodMetadata[] annotatedMethods;
private final MergedAnnotations annotations;
@Nullable
private Set<String> annotationTypes;
@Override
public String getClassName() {
return this.className;
}
@Override
@Nullable
public String getEnclosingClassName() {
return this.enclosingClassName;
}
@Override
@Nullable
public String getSuperClassName() {
return this.superClassName;
}
@Override
public String[] getInterfaceNames() {
return this.interfaceNames.clone();
}
@Override
public String[] getMemberClassNames() {
return this.memberClassNames.clone();
}
@Override
public MergedAnnotations getAnnotations() {
return this.annotations;
}
}
4.1.2 构造方法
SimpleAnnotationMetadata 类只有一个传入全属性值的构造方法,其直接将对应属性值初始化为传入的对应参数值;
final class SimpleAnnotationMetadata implements AnnotationMetadata {
SimpleAnnotationMetadata(String className, int access, @Nullable String enclosingClassName,
@Nullable String superClassName, boolean independentInnerClass, String[] interfaceNames,
String[] memberClassNames, MethodMetadata[] annotatedMethods, MergedAnnotations annotations) {
this.className = className;
this.access = access;
this.enclosingClassName = enclosingClassName;
this.superClassName = superClassName;
this.independentInnerClass = independentInnerClass;
this.interfaceNames = interfaceNames;
this.memberClassNames = memberClassNames;
this.annotatedMethods = annotatedMethods;
this.annotations = annotations;
}
}
4.2 AnnotationMetadata 接口实现
SimpleAnnotationMetadata 类的 isInterface、isAnnotation、isAbstract 及 isFinal 方法都是直接返回 access 属性对应位是否不为 0,其中 0x0200 位标识是否为接口, 0x2000 位标识是否为注解类, 0x0400 位标识是否为抽象类及 0x0010 位标识是否为 final 修饰类;
final class SimpleAnnotationMetadata implements AnnotationMetadata {
@Override
public boolean isInterface() {
return (this.access & Opcodes.ACC_INTERFACE) != 0;
}
@Override
public boolean isAnnotation() {
return (this.access & Opcodes.ACC_ANNOTATION) != 0;
}
@Override
public boolean isAbstract() {
return (this.access & Opcodes.ACC_ABSTRACT) != 0;
}
@Override
public boolean isFinal() {
return (this.access & Opcodes.ACC_FINAL) != 0;
}
}
isIndependent 方法在 enclosingClassName 为空或 independentInnerClass 属性为真,即其不是非静态内部类时返回 true;
final class SimpleAnnotationMetadata implements AnnotationMetadata {
@Override
public boolean isIndependent() {
return (this.enclosingClassName == null || this.independentInnerClass);
}
}
getAnnotationTypes 方法首先在 annotationTypes 属性为 null 时将该属性值初始化为 AnnotationMetadata 接口的 getAnnotationTypes 方法执行结果;
final class SimpleAnnotationMetadata implements AnnotationMetadata {
@Override
public Set<String> getAnnotationTypes() {
Set<String> annotationTypes = this.annotationTypes;
if (annotationTypes == null) {
annotationTypes = Collections.unmodifiableSet(
AnnotationMetadata.super.getAnnotationTypes());
this.annotationTypes = annotationTypes;
}
return annotationTypes;
}
}
getAnnotatedMethods 方法从 annotatedMethods 属性中寻找所有使用名为 annotationName 注解修饰的方法对象保存到 Set 集合中并返回该集合;
final class SimpleAnnotationMetadata implements AnnotationMetadata {
@Override
public Set<MethodMetadata> getAnnotatedMethods(String annotationName) {
Set<MethodMetadata> annotatedMethods = null;
for (MethodMetadata annotatedMethod : this.annotatedMethods) {
if (annotatedMethod.isAnnotated(annotationName)) {
if (annotatedMethods == null) {
annotatedMethods = new LinkedHashSet<>(4);
}
annotatedMethods.add(annotatedMethod);
}
}
return annotatedMethods != null ? annotatedMethods : Collections.emptySet();
}
}
5 StandardMethodMetadata 类
5.1 属性与构造方法
5.1.1 属性变量
StandardMethodMetadata 类拥有保存封装方法对象的 introspectedMethod、标识是否级联查询注解属性 nestedAnnotationsAsMap 及方法所使用的注解封装对象 mergedAnnotations 三个属性;
public class StandardMethodMetadata implements MethodMetadata {
private final Method introspectedMethod;
private final boolean nestedAnnotationsAsMap;
private final MergedAnnotations mergedAnnotations;
@Override
public MergedAnnotations getAnnotations() {
return this.mergedAnnotations;
}
public final Method getIntrospectedMethod() {
return this.introspectedMethod;
}
}
5.1.2 构造方法
StandardMethodMetadata 类也有两个构造方法,在该对象创建过程中首先对 introspectedMethod 参数进行非空验证,随后分别将 introspectedMethod 与 nestedAnnotationsAsMap 属性初始化为对应参数值,最后将 mergedAnnotations 属性初始化为 MergedAnnotations 的 from 方法执行结果;
public class StandardMethodMetadata implements MethodMetadata {
@Deprecated
public StandardMethodMetadata(Method introspectedMethod) {
this(introspectedMethod, false);
}
@Deprecated
public StandardMethodMetadata(Method introspectedMethod, boolean nestedAnnotationsAsMap) {
Assert.notNull(introspectedMethod, "Method must not be null");
this.introspectedMethod = introspectedMethod;
this.nestedAnnotationsAsMap = nestedAnnotationsAsMap;
this.mergedAnnotations = MergedAnnotations.from(
introspectedMethod, SearchStrategy.DIRECT, RepeatableContainers.none());
}
}
5.2 MethodMetadata 接口实现
getMethodName、getDeclaringClassName 与 getReturnTypeName 方法都是获取 introspectedMethod 属性的对应属性的 name 值;
public class StandardMethodMetadata implements MethodMetadata {
@Override
public String getMethodName() {
return this.introspectedMethod.getName();
}
@Override
public String getDeclaringClassName() {
return this.introspectedMethod.getDeclaringClass().getName();
}
@Override
public String getReturnTypeName() {
return this.introspectedMethod.getReturnType().getName();
}
}
isAbstract、isStatic、isFinal、isOverridable 与 isPrivate 方法都是调用 Modifier 的对应方法判断 introspectedMethod 属性的 modifiers 属性是否满足指定条件;
public class StandardMethodMetadata implements MethodMetadata {
@Override
public boolean isAbstract() {
return Modifier.isAbstract(this.introspectedMethod.getModifiers());
}
@Override
public boolean isStatic() {
return Modifier.isStatic(this.introspectedMethod.getModifiers());
}
@Override
public boolean isFinal() {
return Modifier.isFinal(this.introspectedMethod.getModifiers());
}
@Override
public boolean isOverridable() {
return !isStatic() && !isFinal() && !isPrivate();
}
private boolean isPrivate() {
return Modifier.isPrivate(this.introspectedMethod.getModifiers());
}
}
5.3 AnnotatedTypeMetadata 接口实现
5.3.1 getAnnotationAttributes 方法
getAnnotationAttributes 方法在 nestedAnnotationsAsMap 属性为 true 时直接返回 MethodMetadata 的 getAnnotationAttributes 方法执行结果,否则返回 AnnotatedElementUtils 类的静态方法 getMergedAnnotationAttributes 执行结果;
public class StandardMethodMetadata implements MethodMetadata {
@Override
@Nullable
public Map<String, Object> getAnnotationAttributes(String annotationName, boolean classValuesAsString) {
if (this.nestedAnnotationsAsMap) {
return MethodMetadata.super.getAnnotationAttributes(annotationName, classValuesAsString);
}
return AnnotatedElementUtils.getMergedAnnotationAttributes(this.introspectedMethod,
annotationName, classValuesAsString, false);
}
}
5.3.2 getAllAnnotationAttributes 方法
getAllAnnotationAttributes 方法在 nestedAnnotationsAsMap 属性为 true 时直接返回 MethodMetadata 的 getAllAnnotationAttributes 方法执行结果,否则返回 AnnotatedElementUtils 类的静态方法 getAllAnnotationAttributes 执行结果;
public class StandardMethodMetadata implements MethodMetadata {
@Override
@Nullable
public MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationName, boolean classValuesAsString) {
if (this.nestedAnnotationsAsMap) {
return MethodMetadata.super.getAllAnnotationAttributes(annotationName, classValuesAsString);
}
return AnnotatedElementUtils.getAllAnnotationAttributes(this.introspectedMethod,
annotationName, classValuesAsString, false);
}
}
6 SimpleMethodMetadata 类
6.1 属性与构造方法
6.1.1 属性变量
SimpleMethodMetadata 类拥有保存封装方法对象名的 methodName、保存方法类型位图的 access、保存其所在类名的 declaringClassName、保存方法返回类型名 returnTypeName 及修饰方法所使用的注解封装对象 mergedAnnotations 五个属性;
final class SimpleMethodMetadata implements MethodMetadata {
private final String methodName;
private final int access;
private final String declaringClassName;
private final String returnTypeName;
private final MergedAnnotations annotations;
@Override
public String getMethodName() {
return this.methodName;
}
@Override
public String getDeclaringClassName() {
return this.declaringClassName;
}
@Override
public String getReturnTypeName() {
return this.returnTypeName;
}
@Override
public MergedAnnotations getAnnotations() {
return this.annotations;
}
}
6.1.2 构造方法
SimpleMethodMetadata 类只有一个全参数构造方法,其在创建对象的过程中之间会传入所有属性相应入参,并将所有属性更新为对应入参值;
public class StandardMethodMetadata implements MethodMetadata {
@Deprecated
public StandardMethodMetadata(Method introspectedMethod) {
this(introspectedMethod, false);
}
@Deprecated
public StandardMethodMetadata(Method introspectedMethod, boolean nestedAnnotationsAsMap) {
Assert.notNull(introspectedMethod, "Method must not be null");
this.introspectedMethod = introspectedMethod;
this.nestedAnnotationsAsMap = nestedAnnotationsAsMap;
this.mergedAnnotations = MergedAnnotations.from(
introspectedMethod, SearchStrategy.DIRECT, RepeatableContainers.none());
}
}
6.2 MethodMetadata 接口实现
isAbstract、isStatic、isFinal、isOverridable 与 isPrivate 方法都是直接返回 access 对应位是否不为 0;
public class SimpleMethodMetadata implements MethodMetadata {
@Override
public boolean isAbstract() {
return (this.access & Opcodes.ACC_ABSTRACT) != 0;
}
@Override
public boolean isStatic() {
return (this.access & Opcodes.ACC_STATIC) != 0;
}
@Override
public boolean isFinal() {
return (this.access & Opcodes.ACC_FINAL) != 0;
}
@Override
public boolean isOverridable() {
return !isStatic() && !isFinal() && !isPrivate();
}
public boolean isPrivate() {
return (this.access & Opcodes.ACC_PRIVATE) != 0;
}
}
二 SimpleMetadataReader 类
1 MetadataReader 接口
MetadataReader 接口向外提供获取类文件相关对象功能,其中 getResource 方法用于获取类资源对象,getClassMetadata 方法则用于获取类元数据封装对象及 getAnnotationMetadata 方法则是获取可以处理注解的 AnnotationMetadata 类元数据对象;
public interface MetadataReader {
Resource getResource();
ClassMetadata getClassMetadata();
AnnotationMetadata getAnnotationMetadata();
}
2 属性及构造方法
2.1 常量
SimpleMetadataReader 类只有一个 PARSING_OPTIONS 常量,其保存了解析过程中跳过某些属性标识,在使用 classReader 读取解析类资源文件时使用;
final class SimpleMetadataReader implements MetadataReader {
private static final int PARSING_OPTIONS = ClassReader.SKIP_DEBUG
| ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES;
}
2.2 类变量
SimpleMetadataReader 类拥有两个属性,resource 属性保存的是对应类对象的 Resource 资源对象,annotationMetadata 则保存的是对当前关联类对象的封装;
final class SimpleMetadataReader implements MetadataReader {
private final Resource resource;
private final AnnotationMetadata annotationMetadata;
}
2.3 构造方法
SimpleMetadataReader 类在对象创建过程中首先使用 classLoader 参数创建的 SimpleAnnotationMetadataReadingVisitor 对象并将其保存到 visitor 变量中,同时将 resource 属性值初始化 resource 参数值;随后使用 getClassReader 方法创建 resource 关联 getClassReader 读取器并调用该读取器的 accept 方法将属性值保存到 visitor 变量中,同时将 annotationMetadata 属性值初始化为 visitor 变量的 getMetadata 方法的执行结果值;
final class SimpleMetadataReader implements MetadataReader {
SimpleMetadataReader(Resource resource, @Nullable ClassLoader classLoader) throws IOException {
SimpleAnnotationMetadataReadingVisitor visitor = new SimpleAnnotationMetadataReadingVisitor(classLoader);
getClassReader(resource).accept(visitor, PARSING_OPTIONS);
this.resource = resource;
this.annotationMetadata = visitor.getMetadata();
}
}
getClassReader 方法首先使用 resource 方法获取关联 InputStream 输入流对象并返回使用该对象创建的 ClassReader 对象;
final class SimpleMetadataReader implements MetadataReader {
private static ClassReader getClassReader(Resource resource) throws IOException {
try (InputStream is = resource.getInputStream()) {
try {
return new ClassReader(is);
}
catch (IllegalArgumentException ex) {
throw new NestedIOException("ASM ClassReader failed to parse class file - " +
"probably due to a new Java class file version that isn't supported yet: " + resource, ex);
}
}
}
}
3 MetadataReader 接口实现
getResource 方法直接获取 resource 属性值,而 getClassMetadata 与 getAnnotationMetadata 方法则是直接返回 annotationMetadata 属性值;
final class SimpleMetadataReader implements MetadataReader {
@Override
public Resource getResource() {
return this.resource;
}
@Override
public ClassMetadata getClassMetadata() {
return this.annotationMetadata;
}
@Override
public AnnotationMetadata getAnnotationMetadata() {
return this.annotationMetadata;
}
}
三 Visitor 访问器
Spring 为了更好的获取与保存,其对 asm 中使用的某些 visitor 访问器类进行重写,其中 SimpleAnnotationMetadataReadingVisitor 类重写了 ClassVisitor 抽象类,用来提供对类元数据的访问;MergedAnnotationReadingVisitor 类则是 AnnotationVisitor 抽象类的重写,用于解析其中使用的注解;MethodVisitor 抽象类的重写类为 SimpleMethodMetadataReadingVisitor,其用于访问类元数据方法;
1 SimpleAnnotationMetadataReadingVisitor 类
1.1 ClassVisitor 抽象类
1.1.1 属性与构造方法
ClassVisitor 抽象类拥有两个属性变量,其中 api 用于标识当前 asm 版本,cv 属性则是内部 ClassVisitor 对象;ClassVisitor 的构造方法则是将 api 与 cv 属性初始化为对应参数值。
public abstract class ClassVisitor {
protected final int api;
protected ClassVisitor cv;
public ClassVisitor(final int api) {
this(api, null);
}
@SuppressWarnings("deprecation")
public ClassVisitor(final int api, final ClassVisitor classVisitor) {
if (api != Opcodes.ASM7
&& api != Opcodes.ASM6
&& api != Opcodes.ASM5
&& api != Opcodes.ASM4
&& api != Opcodes.ASM8_EXPERIMENTAL) {
throw new IllegalArgumentException("Unsupported api " + api);
}
this.api = api;
this.cv = classVisitor;
}
}
1.1.2 方法
ClassVisitor 抽象类的所有方法都是在 cv 属性不为 null 时直接执行其的对应方法并返回执行结果,由于 SimpleAnnotationMetadataReadingVisitor 在创建对象的过程中直接将 cv 属性初始化为 null,即其未实现方法不会执行任何逻辑;
public abstract class ClassVisitor {
public void visit(
final int version,
final int access,
final String name,
final String signature,
final String superName,
final String[] interfaces) {
if (cv != null) {
cv.visit(version, access, name, signature, superName, interfaces);
}
}
public void visitSource(final String source, final String debug) {
if (cv != null) {
cv.visitSource(source, debug);
}
}
public ModuleVisitor visitModule(final String name, final int access, final String version) {
if (api < Opcodes.ASM6) {
throw new UnsupportedOperationException("This feature requires ASM6");
}
if (cv != null) {
return cv.visitModule(name, access, version);
}
return null;
}
public void visitNestHost(final String nestHost) {
if (api < Opcodes.ASM7) {
throw new UnsupportedOperationException("This feature requires ASM7");
}
if (cv != null) {
cv.visitNestHost(nestHost);
}
}
public void visitOuterClass(final String owner, final String name, final String descriptor) {
if (cv != null) {
cv.visitOuterClass(owner, name, descriptor);
}
}
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
if (cv != null) {
return cv.visitAnnotation(descriptor, visible);
}
return null;
}
public AnnotationVisitor visitTypeAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
if (api < Opcodes.ASM5) {
throw new UnsupportedOperationException("This feature requires ASM5");
}
if (cv != null) {
return cv.visitTypeAnnotation(typeRef, typePath, descriptor, visible);
}
return null;
}
public void visitAttribute(final Attribute attribute) {
if (cv != null) {
cv.visitAttribute(attribute);
}
}
public void visitNestMember(final String nestMember) {
if (api < Opcodes.ASM7) {
throw new UnsupportedOperationException("This feature requires ASM7");
}
if (cv != null) {
cv.visitNestMember(nestMember);
}
}
@Deprecated
public void visitPermittedSubtypeExperimental(final String permittedSubtype) {
if (api != Opcodes.ASM8_EXPERIMENTAL) {
throw new UnsupportedOperationException("This feature requires ASM8_EXPERIMENTAL");
}
if (cv != null) {
cv.visitPermittedSubtypeExperimental(permittedSubtype);
}
}
public void visitInnerClass(
final String name, final String outerName, final String innerName, final int access) {
if (cv != null) {
cv.visitInnerClass(name, outerName, innerName, access);
}
}
@Deprecated
public RecordComponentVisitor visitRecordComponentExperimental(
final int access, final String name, final String descriptor, final String signature) {
if (api < Opcodes.ASM8_EXPERIMENTAL) {
throw new UnsupportedOperationException("This feature requires ASM8_EXPERIMENTAL");
}
if (cv != null) {
return cv.visitRecordComponentExperimental(access, name, descriptor, signature);
}
return null;
}
public FieldVisitor visitField(
final int access,
final String name,
final String descriptor,
final String signature,
final Object value) {
if (cv != null) {
return cv.visitField(access, name, descriptor, signature, value);
}
return null;
}
public MethodVisitor visitMethod(
final int access,
final String name,
final String descriptor,
final String signature,
final String[] exceptions) {
if (cv != null) {
return cv.visitMethod(access, name, descriptor, signature, exceptions);
}
return null;
}
public void visitEnd() {
if (cv != null) {
cv.visitEnd();
}
}
}
1.2 属性与构造方法
1.2.1 属性变量
SimpleAnnotationMetadataReadingVisitor 类的 classLoader 属性保存用于保存访问器所使用的类加载器,className 属性保存的是类资源对应的外部类名、access 则是类相关访问属性位图、superClassName 属性则是其直接父类名、interfaceNames 属性保存的是类所实现的所有接口名数组,enclosingClassName 则是其外部类名、independentInnerClass 标识其是否拥有独立内部类,memberClassNames 则是其内部类名 set 集合属性,annotations 属性保存的是修饰类的注解 MergedAnnotation 封装列表,annotatedMethods 则是使用 SimpleMethodMetadata 封装的非静态方法列表、metadata 保存的是类元数据对象,最后一个属性为保存类资源的 source 属性;
final class SimpleAnnotationMetadataReadingVisitor extends ClassVisitor {
@Nullable
private final ClassLoader classLoader;
private String className = "";
private int access;
@Nullable
private String superClassName;
private String[] interfaceNames = new String[0];
@Nullable
private String enclosingClassName;
private boolean independentInnerClass;
private Set<String> memberClassNames = new LinkedHashSet<>(4);
private List<MergedAnnotation<?>> annotations = new ArrayList<>();
private List<SimpleMethodMetadata> annotatedMethods = new ArrayList<>();
@Nullable
private SimpleAnnotationMetadata metadata;
@Nullable
private Source source;
}
1.2.2 构造方法
SimpleAnnotationMetadataReadingVisitor 类只有一个拥有类加载器对象参数的构造方法,在创建对象的过程中使用 SpringAsmInfo 的 ASM_VERSION 常量值调用父对象的构造方法,同时将 classLoader 属性初始化为 classLoader 参数值;
final class SimpleAnnotationMetadataReadingVisitor extends ClassVisitor {
SimpleAnnotationMetadataReadingVisitor(@Nullable ClassLoader classLoader) {
super(SpringAsmInfo.ASM_VERSION);
this.classLoader = classLoader;
}
}
1.3 visit 方法
visit 方法为 Visitor 访问器中第一个被访问的方法,其主要功能为访问类基础设置,即设置在类定义标签的相关信息;其中 name 属性为解析出来的类路径,在方法执行过程中将其中的 / 字符串替换为 . ,即将其装好为全限定类名然后将 className 属性值更新为转换后的字符串值;acess 参数为类的相关属性,具体标识位在 Opcodes 中的 ACC 开头的常量中声明,在创建过程中直接将 acess 属性更新为该参数值;supername 参数为类的直接父类名,在类不为接口时将 supername 属性更新为该值;最后一个 interfaces 参数为类实现的接口数组,spring 将其中元素转化为全限定类名并保存到 interfaceNames 属性中;
final class SimpleAnnotationMetadataReadingVisitor extends ClassVisitor {
@Override
public void visit(int version, int access, String name, String signature,
@Nullable String supername, String[] interfaces) {
this.className = toClassName(name);
this.access = access;
if (supername != null && !isInterface(access)) {
this.superClassName = toClassName(supername);
}
this.interfaceNames = new String[interfaces.length];
for (int i = 0; i < interfaces.length; i++) {
this.interfaceNames[i] = toClassName(interfaces[i]);
}
}
}
1.4 visitOuterClass 方法
visitOuterClass 方法则是访问其外部类,其中 owner 为其外部类名路径,在重写的该方法中直接将 enclosingClassName 属性更新为 owner 参数转化出的全限定类名;
final class SimpleAnnotationMetadataReadingVisitor extends ClassVisitor {
@Override
public void visitOuterClass(String owner, String name, String desc) {
this.enclosingClassName = toClassName(owner);
}
}
1.5 visitInnerClass 方法
visitInnerClass 方法则是用于访问内部类,其中 name 参数值为外部类路径$内部类简单名、outerName 参数则是外部类路径、innerName 参数则是简单内部类名、最后一个参数为保存内部类相关属性的 access;方法执行过程中,在 outerName 参数为 null 时直接返回,否则在 className 属性值与 name 对应值一致时,将 enclosingClassName 属性值更新为 outerName 参数转换出的外部类类名,并将 independentInnerClass 属性值更新为当前类是否为静态类,否则在 className 属性值与 outerName 对应类名一致时直接将 name 参数转化出的全限定类名值添加到 memberClassNames 属性中。
final class SimpleAnnotationMetadataReadingVisitor extends ClassVisitor {
@Override
public void visitInnerClass(String name, @Nullable String outerName, String innerName,
int access) {
if (outerName != null) {
String className = toClassName(name);
String outerClassName = toClassName(outerName);
if (this.className.equals(className)) {
this.enclosingClassName = outerClassName;
this.independentInnerClass = ((access & Opcodes.ACC_STATIC) != 0);
}
else if (this.className.equals(outerClassName)) {
this.memberClassNames.add(className);
}
}
}
}
1.6 visitAnnotation 方法
visitAnnotation 方法则是获取类注解访问器;该方法拥有两个参数,descriptor 为注解类的类路径,visible 参数则是用于标识注解是否为运行时可见(使用 RetentionPolicy. RUNTIME 策略的 Retention 元注解修饰),该方法直接使用 classLoader 属性、getSource 方法执行结果、descriptor 、visible 参数及 annotations 属性的 add 方法调用 MergedAnnotationReadingVisitor 类的 get 方法获取对应的注解访问对象并返回。
final class SimpleAnnotationMetadataReadingVisitor extends ClassVisitor {
@Override
@Nullable
public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
return MergedAnnotationReadingVisitor.get(this.classLoader, this::getSource,
descriptor, visible, this.annotations::add);
}
}
1.7 visitMethod 方法
visitAnnotation 方法用于获取方法访问器;其拥有 access 方法修饰位图、方法名 name、保存方法参数类型,包含形参类型(使用 () 进行包裹并使用 ; 进行分隔)与返参类型的 descriptor 、signature 签名及方法异常签名数组 exceptions 参数;该方法在访问桥接方法时返回 null,否则使用 classLoader、className 属性、access、name、 descriptor参数及 annotatedMethods 属性的 add 方法创建 SimpleMethodMetadataReadingVisitor 对象并返回;
final class SimpleAnnotationMetadataReadingVisitor extends ClassVisitor {
public MethodVisitor visitMethod(
int access, String name, String descriptor, String signature, String[] exceptions) {
if (isBridge(access)) {
return null;
}
return new SimpleMethodMetadataReadingVisitor(this.classLoader, this.className,
access, name, descriptor, this.annotatedMethods::add);
}
}
1.8 visitEnd 方法
visitEnd 方法为类资源访问结束之后调用的最后一个方法,SimpleAnnotationMetadataReadingVisitor 类中该方法主要目的为更新 metadata 属性;该方法首先将 memberClassNames 属性、annotatedMethods 属性及 annotations 属性值分别转化为 memberClassNames 数组、MethodMetadata 数组及 MergedAnnotations 对象并使用 className、access、enclosingClassName 、superClassName、independentInnerClass、interfaceNames 属性值及上面转化出的三个对象创建 SimpleAnnotationMetadata 对象,最后将其保存到 metadata 属性中;
final class SimpleAnnotationMetadataReadingVisitor extends ClassVisitor {
@Override
public void visitEnd() {
String[] memberClassNames = StringUtils.toStringArray(this.memberClassNames);
MethodMetadata[] annotatedMethods = this.annotatedMethods.toArray(new MethodMetadata[0]);
MergedAnnotations annotations = MergedAnnotations.of(this.annotations);
this.metadata = new SimpleAnnotationMetadata(this.className, this.access,
this.enclosingClassName, this.superClassName, this.independentInnerClass,
this.interfaceNames, memberClassNames, annotatedMethods, annotations);
}
}
2 MergedAnnotationReadingVisitor 类
2.1 AnnotationVisitor 抽象类
AnnotationVisitor 抽象类中的属性与方法与 ClassVisitor 抽象类中一样,只有 api 与 av 两个属性,方法也只是调用内 av 属性的对应方法,因此本处就不做过多介绍了。
public abstract class AnnotationVisitor {
protected final int api;
protected AnnotationVisitor av;
public AnnotationVisitor(final int api) {
this(api, null);
}
@SuppressWarnings("deprecation")
public AnnotationVisitor(final int api, final AnnotationVisitor annotationVisitor) {
if (api != Opcodes.ASM7
&& api != Opcodes.ASM6
&& api != Opcodes.ASM5
&& api != Opcodes.ASM4
&& api != Opcodes.ASM8_EXPERIMENTAL) {
throw new IllegalArgumentException("Unsupported api " + api);
}
this.api = api;
this.av = annotationVisitor;
}
public void visit(final String name, final Object value) {
if (av != null) {
av.visit(name, value);
}
}
public void visitEnum(final String name, final String descriptor, final String value) {
if (av != null) {
av.visitEnum(name, descriptor, value);
}
}
public AnnotationVisitor visitAnnotation(final String name, final String descriptor) {
if (av != null) {
return av.visitAnnotation(name, descriptor);
}
return null;
}
public AnnotationVisitor visitArray(final String name) {
if (av != null) {
return av.visitArray(name);
}
return null;
}
public void visitEnd() {
if (av != null) {
av.visitEnd();
}
}
}
2.2 属性与构造方法
2.2.1 属性变量
MergedAnnotationReadingVisitor 类的 classLoader、source 及 annotationType 三个属性用于存储注解类的相关元属性,分别保存的是注解所使用类加载器、注解资源对象及注解类型对象;除了上述三个用于保存注解元属性的类变量属性之外,还有两个分别用于存储完成注解访问的消费对象的 consumer 及保存当前注解的属性名与值映射的 attributes 属性;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
@Nullable
private final ClassLoader classLoader;
@Nullable
private final Object source;
private final Class<A> annotationType;
private final Consumer<MergedAnnotation<A>> consumer;
private final Map<String, Object> attributes = new LinkedHashMap<>(4);
}
2.2.2 构造方法
MergedAnnotationReadingVisitor 类在创建对象的过程中使用 SpringAsmInfo 的 ASM_VERSION 常量值调用父对象的构造方法,同时将除 attributes 属性之外的所有属性值初始化为对应参数值;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
public MergedAnnotationReadingVisitor(@Nullable ClassLoader classLoader, @Nullable Object source,
Class<A> annotationType, Consumer<MergedAnnotation<A>> consumer) {
super(SpringAsmInfo.ASM_VERSION);
this.classLoader = classLoader;
this.source = source;
this.annotationType = annotationType;
this.consumer = consumer;
}
}
2.3 get 静态方法
由于 SimpleAnnotationMetadataReadingVisitor 类中使用 get 静态方法创建并获取 MergedAnnotationReadingVisitor 对象,因此我们首先对 get 方法进行分析;get 方法首先在 visible 参数值为 false 时直接返回 null;随后使用 AnnotationFilter 的 PLAIN 常量值的 matches 方法注解来过滤 java.lang 与 org.springframework.lang 包下的所有注解,最后在 sourceSupplier 参数不为空时使用其 get 方法执行结果值、注解类型对象、classLoader 参数及 consumer 参数创建 MergedAnnotationReadingVisitor 对象并返回;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
@Nullable
static <A extends Annotation> AnnotationVisitor get(@Nullable ClassLoader classLoader,
@Nullable Supplier<Object> sourceSupplier, String descriptor, boolean visible,
Consumer<MergedAnnotation<A>> consumer) {
if (!visible) {
return null;
}
String typeName = Type.getType(descriptor).getClassName();
if (AnnotationFilter.PLAIN.matches(typeName)) {
return null;
}
Object source = (sourceSupplier != null ? sourceSupplier.get() : null);
try {
Class<A> annotationType = (Class<A>) ClassUtils.forName(typeName, classLoader);
return new MergedAnnotationReadingVisitor<>(classLoader, source, annotationType, consumer);
}
catch (ClassNotFoundException | LinkageError ex) {
return null;
}
}
}
2.4 visit 方法
visit 方法用于访问注解中除枚举、注解类型、非空数组、非 class 类型数组及非注解类型数组的属性,若值为 Class 对象则会将 value 值更新为类名,最后将 name 属性名称与 value 属性值映射保存到 attributes 属性中;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
@Override
public void visit(String name, Object value) {
if (value instanceof Type) {
value = ((Type) value).getClassName();
}
this.attributes.put(name, value);
}
}
2.5 visitEnum 方法
visitEnum 方法用于访问注解中枚举类型属性,其首先使用类加载器属性加载属性值对应的 class 对象,最后调用 Enum 类的 valueOf 静态方法获取 value 值对应枚举值并将其与 name 参数的映射添加到 attributes 属性中;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
@Override
public void visitEnum(String name, String descriptor, String value) {
visitEnum(descriptor, value, enumValue -> this.attributes.put(name, enumValue));
}
public <E extends Enum<E>> void visitEnum(String descriptor, String value, Consumer<E> consumer) {
String className = Type.getType(descriptor).getClassName();
Class<E> type = (Class<E>) ClassUtils.resolveClassName(className, this.classLoader);
consumer.accept(Enum.valueOf(type, value));
}
}
2.6 visitAnnotation 方法
visitAnnotation 方法用于访问注解中注解类型属性,其使用 AnnotationFilter 的 PLAIN 常量值的 matches 方法注解来过滤 java.lang 与 org.springframework.lang 包下的注解进行过滤,否则使用类加载器属性加载注解对应的 class 对象并使用 classLoader 属性、source 属性、注解类型及向 attributes 属性中添加 name 与注解对象映射消费方法创建 MergedAnnotationReadingVisitor 对象随后返回;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
@Override
@Nullable
public AnnotationVisitor visitAnnotation(String name, String descriptor) {
return visitAnnotation(descriptor, annotation -> this.attributes.put(name, annotation));
}
@Nullable
private <T extends Annotation> AnnotationVisitor visitAnnotation(
String descriptor, Consumer<MergedAnnotation<T>> consumer) {
String className = Type.getType(descriptor).getClassName();
if (AnnotationFilter.PLAIN.matches(className)) {
return null;
}
Class<T> type = (Class<T>) ClassUtils.resolveClassName(className, this.classLoader);
return new MergedAnnotationReadingVisitor<>(this.classLoader, this.source, type, consumer);
}
}
2.7 visitArray 方法
visitArray 方法用于访问注解中空数组、class 类型数组及注解类型数组属性,其直接使用向 attributes 属性中添加 name 属性名与消费参数映射值的消费方法创建 ArrayVisitor 对象并返回;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
@Override
public AnnotationVisitor visitArray(String name) {
return new ArrayVisitor(value -> this.attributes.put(name, value));
}
}
2.7.1 ArrayVisitor 内部类
1)属性与构造方法
ArrayVisitor 内部类作为空数组、class 类型数组及注解类型数组的访问器,继承自 AnnotationVisitor 抽象类,其拥有两个属性,elements 属性用于存储访问过程中获取到的数组对象列表,consumer 属性则用于完成数组访问后对 elements 属性的消费;
ArrayVisitor 内部类只有一个 consumer 参数,创建过程中首先使用 SpringAsmInfo.ASM_VERSION 常量执行父类的构造方法,同时将 consumer 属性初始化为 consumer 参数值;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
private class ArrayVisitor extends AnnotationVisitor {
private final List<Object> elements = new ArrayList<>();
private final Consumer<Object[]> consumer;
ArrayVisitor(Consumer<Object[]> consumer) {
super(SpringAsmInfo.ASM_VERSION);
this.consumer = consumer;
}
}
}
2)visit 方法
visit 方法在属性为 class 类对象时会将 value 值更新为类名,随后将 value 值保存到 elements 属性中;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
private class ArrayVisitor extends AnnotationVisitor {
@Override
public void visit(String name, Object value) {
if (value instanceof Type) {
value = ((Type) value).getClassName();
}
this.elements.add(value);
}
}
}
3)visitEnum 方法
visitEnum 方法调用当前外部 MergedAnnotationReadingVisitor 对象的 visitEnum 方法,其中的 consumer 参数值为 elements 属性的 add 方法;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
private class ArrayVisitor extends AnnotationVisitor {
@Override
public void visitEnum(String name, String descriptor, String value) {
MergedAnnotationReadingVisitor.this.visitEnum(descriptor, value, this.elements::add);
}
}
}
4)visitAnnotation 方法
visitAnnotation 方法调用当前外部 MergedAnnotationReadingVisitor 对象的 visitAnnotation 方法,其中的 consumer 参数值也是 elements 属性的 add 方法;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
private class ArrayVisitor extends AnnotationVisitor {
@Override
@Nullable
public AnnotationVisitor visitAnnotation(String name, String descriptor) {
return MergedAnnotationReadingVisitor.this.visitAnnotation(descriptor, this.elements::add);
}
}
}
5)visitEnd 方法
visitEnd 方法首先通过 getComponentType 方法获取 elements 属性中元素对应的 class 类型对象并使用其与 elements 容量大小创建对应数组,最后将 elements 属性转化为该数组并调用 consumer 属性的 accpet 方法消费该数组;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
private class ArrayVisitor extends AnnotationVisitor {
@Override
public void visitEnd() {
Class<?> componentType = getComponentType();
Object[] array = (Object[]) Array.newInstance(componentType, this.elements.size());
this.consumer.accept(this.elements.toArray(array));
}
}
}
getComponentType 方法在 elements 属性没有任意元素时直接返回 Object 类型,否则获取其第一个元素值并在其为枚举时调用 getDeclaringClass 返回枚举类型否则直接返回其 getClass 结果值;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
private class ArrayVisitor extends AnnotationVisitor {
private Class<?> getComponentType() {
if (this.elements.isEmpty()) {
return Object.class;
}
Object firstElement = this.elements.get(0);
if (firstElement instanceof Enum) {
return ((Enum<?>) firstElement).getDeclaringClass();
}
return firstElement.getClass();
}
}
}
2.8 visitEnd 方法
visitEnd 方法首先调用 MergedAnnotation 类的 of 静态方法创建 MergedAnnotation 对象并调用 consumer 属性的 accept 方法对其进行消费;
class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVisitor {
@Override
public void visitEnd() {
MergedAnnotation<A> annotation = MergedAnnotation.of(
this.classLoader, this.source, this.annotationType, this.attributes);
this.consumer.accept(annotation);
}
}
3 SimpleMethodMetadataReadingVisitor 类
3.1 MethodVisitor 抽象类
AnnotationVisitor 抽象类中的属性与方法与 ClassVisitor 抽象类中一样,只有 api 与 mv 两个属性,方法也只是调用内 mv 属性的对应方法,因此本处就不做过多介绍了。
public abstract class MethodVisitor {
private static final String REQUIRES_ASM5 = "This feature requires ASM5";
protected final int api;
protected MethodVisitor mv;
public MethodVisitor(final int api) {
this(api, null);
}
@SuppressWarnings("deprecation")
public MethodVisitor(final int api, final MethodVisitor methodVisitor) {
if (api != Opcodes.ASM7
&& api != Opcodes.ASM6
&& api != Opcodes.ASM5
&& api != Opcodes.ASM4
&& api != Opcodes.ASM8_EXPERIMENTAL) {
throw new IllegalArgumentException("Unsupported api " + api);
}
this.api = api;
this.mv = methodVisitor;
}
public void visitParameter(final String name, final int access) {
if (api < Opcodes.ASM5) {
throw new UnsupportedOperationException(REQUIRES_ASM5);
}
if (mv != null) {
mv.visitParameter(name, access);
}
}
public AnnotationVisitor visitAnnotationDefault() {
if (mv != null) {
return mv.visitAnnotationDefault();
}
return null;
}
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
if (mv != null) {
return mv.visitAnnotation(descriptor, visible);
}
return null;
}
public AnnotationVisitor visitTypeAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
if (api < Opcodes.ASM5) {
throw new UnsupportedOperationException(REQUIRES_ASM5);
}
if (mv != null) {
return mv.visitTypeAnnotation(typeRef, typePath, descriptor, visible);
}
return null;
}
public void visitAnnotableParameterCount(final int parameterCount, final boolean visible) {
if (mv != null) {
mv.visitAnnotableParameterCount(parameterCount, visible);
}
}
public AnnotationVisitor visitParameterAnnotation(
final int parameter, final String descriptor, final boolean visible) {
if (mv != null) {
return mv.visitParameterAnnotation(parameter, descriptor, visible);
}
return null;
}
public void visitAttribute(final Attribute attribute) {
if (mv != null) {
mv.visitAttribute(attribute);
}
}
public void visitCode() {
if (mv != null) {
mv.visitCode();
}
}
public void visitFrame(
final int type,
final int numLocal,
final Object[] local,
final int numStack,
final Object[] stack) {
if (mv != null) {
mv.visitFrame(type, numLocal, local, numStack, stack);
}
}
public void visitInsn(final int opcode) {
if (mv != null) {
mv.visitInsn(opcode);
}
}
public void visitIntInsn(final int opcode, final int operand) {
if (mv != null) {
mv.visitIntInsn(opcode, operand);
}
}
public void visitVarInsn(final int opcode, final int var) {
if (mv != null) {
mv.visitVarInsn(opcode, var);
}
}
public void visitTypeInsn(final int opcode, final String type) {
if (mv != null) {
mv.visitTypeInsn(opcode, type);
}
}
public void visitFieldInsn(
final int opcode, final String owner, final String name, final String descriptor) {
if (mv != null) {
mv.visitFieldInsn(opcode, owner, name, descriptor);
}
}
@Deprecated
public void visitMethodInsn(
final int opcode, final String owner, final String name, final String descriptor) {
int opcodeAndSource = opcode | (api < Opcodes.ASM5 ? Opcodes.SOURCE_DEPRECATED : 0);
visitMethodInsn(opcodeAndSource, owner, name, descriptor, opcode == Opcodes.INVOKEINTERFACE);
}
public void visitMethodInsn(
final int opcode,
final String owner,
final String name,
final String descriptor,
final boolean isInterface) {
if (api < Opcodes.ASM5 && (opcode & Opcodes.SOURCE_DEPRECATED) == 0) {
if (isInterface != (opcode == Opcodes.INVOKEINTERFACE)) {
throw new UnsupportedOperationException("INVOKESPECIAL/STATIC on interfaces requires ASM5");
}
visitMethodInsn(opcode, owner, name, descriptor);
return;
}
if (mv != null) {
mv.visitMethodInsn(opcode & ~Opcodes.SOURCE_MASK, owner, name, descriptor, isInterface);
}
}
public void visitInvokeDynamicInsn(
final String name,
final String descriptor,
final Handle bootstrapMethodHandle,
final Object... bootstrapMethodArguments) {
if (api < Opcodes.ASM5) {
throw new UnsupportedOperationException(REQUIRES_ASM5);
}
if (mv != null) {
mv.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
}
}
public void visitJumpInsn(final int opcode, final Label label) {
if (mv != null) {
mv.visitJumpInsn(opcode, label);
}
}
public void visitLabel(final Label label) {
if (mv != null) {
mv.visitLabel(label);
}
}
public void visitLdcInsn(final Object value) {
if (api < Opcodes.ASM5
&& (value instanceof Handle
|| (value instanceof Type && ((Type) value).getSort() == Type.METHOD))) {
throw new UnsupportedOperationException(REQUIRES_ASM5);
}
if (api < Opcodes.ASM7 && value instanceof ConstantDynamic) {
throw new UnsupportedOperationException("This feature requires ASM7");
}
if (mv != null) {
mv.visitLdcInsn(value);
}
}
public void visitIincInsn(final int var, final int increment) {
if (mv != null) {
mv.visitIincInsn(var, increment);
}
}
public void visitTableSwitchInsn(
final int min, final int max, final Label dflt, final Label... labels) {
if (mv != null) {
mv.visitTableSwitchInsn(min, max, dflt, labels);
}
}
public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) {
if (mv != null) {
mv.visitLookupSwitchInsn(dflt, keys, labels);
}
}
public void visitMultiANewArrayInsn(final String descriptor, final int numDimensions) {
if (mv != null) {
mv.visitMultiANewArrayInsn(descriptor, numDimensions);
}
}
public AnnotationVisitor visitInsnAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
if (api < Opcodes.ASM5) {
throw new UnsupportedOperationException(REQUIRES_ASM5);
}
if (mv != null) {
return mv.visitInsnAnnotation(typeRef, typePath, descriptor, visible);
}
return null;
}
public void visitTryCatchBlock(
final Label start, final Label end, final Label handler, final String type) {
if (mv != null) {
mv.visitTryCatchBlock(start, end, handler, type);
}
}
public AnnotationVisitor visitTryCatchAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
if (api < Opcodes.ASM5) {
throw new UnsupportedOperationException(REQUIRES_ASM5);
}
if (mv != null) {
return mv.visitTryCatchAnnotation(typeRef, typePath, descriptor, visible);
}
return null;
}
public void visitLocalVariable(
final String name,
final String descriptor,
final String signature,
final Label start,
final Label end,
final int index) {
if (mv != null) {
mv.visitLocalVariable(name, descriptor, signature, start, end, index);
}
}
public AnnotationVisitor visitLocalVariableAnnotation(
final int typeRef,
final TypePath typePath,
final Label[] start,
final Label[] end,
final int[] index,
final String descriptor,
final boolean visible) {
if (api < Opcodes.ASM5) {
throw new UnsupportedOperationException(REQUIRES_ASM5);
}
if (mv != null) {
return mv.visitLocalVariableAnnotation(
typeRef, typePath, start, end, index, descriptor, visible);
}
return null;
}
public void visitLineNumber(final int line, final Label start) {
if (mv != null) {
mv.visitLineNumber(line, start);
}
}
public void visitMaxs(final int maxStack, final int maxLocals) {
if (mv != null) {
mv.visitMaxs(maxStack, maxLocals);
}
}
public void visitEnd() {
if (mv != null) {
mv.visitEnd();
}
}
}
3.2 属性与构造方法
3.2.1 属性变量
MergedAnnotationReadingVisitor 类的 classLoader、declaringClassName、access、name、source 及 descriptor 六个属性用于存储注解类的相关元属性,分别保存的是方法所使用类加载器、所在类名、方法访问权限位图、方法名、方法对应资源及方法参数列表;除了上述保存注解元属性的类变量属性之外,还有两个分别用于存储完成注解访问的消费对象的 consumer 及保存当前方法上所拥有的注解对象列表 annotations 属性;
final class SimpleMethodMetadataReadingVisitor extends MethodVisitor {
@Nullable
private final ClassLoader classLoader;
private final String declaringClassName;
private final int access;
private final String name;
private final String descriptor;
private final List<MergedAnnotation<?>> annotations = new ArrayList<>(4);
private final Consumer<SimpleMethodMetadata> consumer;
@Nullable
private Source source;
}
3.2.2 构造方法
MergedAnnotationReadingVisitor 类在创建对象的过程中使用 SpringAsmInfo 的 ASM_VERSION 常量值调用父对象的构造方法,同时将除 annotations 属性之外的所有属性值初始化为对应参数值;
final class SimpleMethodMetadataReadingVisitor extends MethodVisitor {
SimpleMethodMetadataReadingVisitor(@Nullable ClassLoader classLoader, String declaringClassName,
int access, String name, String descriptor, Consumer<SimpleMethodMetadata> consumer) {
super(SpringAsmInfo.ASM_VERSION);
this.classLoader = classLoader;
this.declaringClassName = declaringClassName;
this.access = access;
this.name = name;
this.descriptor = descriptor;
this.consumer = consumer;
}
}
3.3 visitAnnotation 方法
visitAnnotation 方法返回方法的注解访问器,其 MergedAnnotationReadingVisitor 类的 get 静态方法,参数为 classLoader 属性、getSource 方法执行结果、descriptor参数、visible 参数及 annotations 属性的 add 方法创建 MergedAnnotationReadingVisitor 对象并返回 ;
final class SimpleMethodMetadataReadingVisitor extends MethodVisitor {
@Override
@Nullable
public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
return MergedAnnotationReadingVisitor.get(this.classLoader, this::getSource,
descriptor, visible, this.annotations::add);
}
}
3.3.1 getSource 方法
getSource 方法在 source 属性值不为 null 时直接返回该值,否则使用 declaringClassName、name 及 descriptor 属性创建 Source 对象并同时将其保存到 source 属性中并返回该值;
final class SimpleMethodMetadataReadingVisitor extends MethodVisitor {
private Object getSource() {
Source source = this.source;
if (source == null) {
source = new Source(this.declaringClassName, this.name, this.descriptor);
this.source = source;
}
return source;
}
}
3.3.2 Source 内部类
1)属性与构造方法
Source 内部类拥有 4 个属性,其中 declaringClassName、name 及 descriptor 三个属性在构造方法中传入,分别保存方法所在类名、方法名及方法参数列表,而 toStringValue 属性用于缓存 Source 对象的 toString 方法执行结果;
Source 内部类只有一个构造方法,其直接 declaringClassName、name 及 descriptor 三个属性初始化为对应参数值;
final class SimpleMethodMetadataReadingVisitor extends MethodVisitor {
static final class Source {
private final String declaringClassName;
private final String name;
private final String descriptor;
@Nullable
private String toStringValue;
}
}
2)属性与构造方法
Source 内部类主要对 toString 方法进行分析,该方法在 toStringValue 属性不为 null 时直接返回该值,否则将 toStringValue 属性值更新为 类名.方法名.(以 , 分割的实参类型) 形式字符串值并返回;
final class SimpleMethodMetadataReadingVisitor extends MethodVisitor {
static final class Source {
@Override
public int hashCode() {
int result = 1;
result = 31 * result + this.declaringClassName.hashCode();
result = 31 * result + this.name.hashCode();
result = 31 * result + this.descriptor.hashCode();
return result;
}
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
Source otherSource = (Source) other;
return (this.declaringClassName.equals(otherSource.declaringClassName) &&
this.name.equals(otherSource.name) && this.descriptor.equals(otherSource.descriptor));
}
@Override
public String toString() {
String value = this.toStringValue;
if (value == null) {
StringBuilder builder = new StringBuilder();
builder.append(this.declaringClassName);
builder.append('.');
builder.append(this.name);
Type[] argumentTypes = Type.getArgumentTypes(this.descriptor);
builder.append('(');
for (int i = 0; i < argumentTypes.length; i++) {
if (i != 0) {
builder.append(',');
}
builder.append(argumentTypes[i].getClassName());
}
builder.append(')');
value = builder.toString();
this.toStringValue = value;
}
return value;
}
}
}
3.3 visitEnd 方法
visitEnd 方法在 annotations 属性中没有任何元素时直接返回,否则利用 annotations 属性执行 MergedAnnotations 类的 of 静态方法创建 MergedAnnotations 对象并利用该对象、name 属性值、access 属性值、declaringClassName 属性值及方法返回值类名创建 SimpleMethodMetadata 对象,最后执行 consumer 属性的 accept 方法对创建对象进行消费;
final class SimpleMethodMetadataReadingVisitor extends MethodVisitor {
@Override
public void visitEnd() {
if (!this.annotations.isEmpty()) {
String returnTypeName = Type.getReturnType(this.descriptor).getClassName();
MergedAnnotations annotations = MergedAnnotations.of(this.annotations);
SimpleMethodMetadata metadata = new SimpleMethodMetadata(this.name,
this.access, this.declaringClassName, returnTypeName, annotations);
this.consumer.accept(metadata);
}
}
}
四 MergedAnnotations 对象
1 MergedAnnotations 接口
1.1 静态方法
1.1.1 from 方法
from 静态方法大致可以分为两类,一类使用 AnnotatedElement 类型参数作为 MergedAnnotations 对象创建来源,另一类则使用 Annotation 类型对象作为对象创建来源;
1)AnnotatedElement 参数方法
最底层的拥有 AnnotatedElement 类型参数的 from 方法拥有 4 个不同参数,其中 element 参数为必传项,在其传入为 null 时直接抛出异常;searchStrategy 参数为对象注解搜索策略,可以传 null,在未传入时默认使用 SearchStrategy.DIRECT;repeatableContainers 参数则定义了搜索时对 Repeatable 注解的支持策略,其默认使用 StandardRepeatableContainers 对象,表明检索过程中需要支持 Repeatable 注解,若不希望支持 Repeatable 注解则直接使用 none 方法获取对象;annotationFilter 参数则是注解对象过滤策略,在传入 null 时会直接抛出异常,未传入时则默认使用 AnnotationFilter.PLAIN 常量值,即过滤掉 java.lang 与 org.springframework.lang 包中注解,除了 PLAIN 外还可以使用用于过滤 java 与 javax 包下所有注解的 JAVA 常量值,ALL 常量则不会过滤任何注解,NONE 常量则是将所有注解过滤掉;该底层方法直接使用 TypeMappedAnnotations 的 from 方法创建 TypeMappedAnnotations 对象并返回;
public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>> {
static MergedAnnotations from(AnnotatedElement element) {
return from(element, SearchStrategy.DIRECT);
}
static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy) {
return from(element, searchStrategy, RepeatableContainers.standardRepeatables());
}
static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,
RepeatableContainers repeatableContainers) {
return from(element, searchStrategy, repeatableContainers, AnnotationFilter.PLAIN);
}
static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,
RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
Assert.notNull(repeatableContainers, "RepeatableContainers must not be null");
Assert.notNull(annotationFilter, "AnnotationFilter must not be null");
return TypeMappedAnnotations.from(element, searchStrategy, repeatableContainers, annotationFilter);
}
}
2)Annotation 参数方法
最底层的拥有 AnnotatedElement 类型参数的 from 方法拥有 4 个不同参数;其中 repeatableContainers 与 annotationFilter 参数与上一方法对应参数一致;annotations 参数为注解来源注解列表,source 参数则是资源对象;其底层也是利用入参值执行 TypeMappedAnnotations 类的 from 方法创建 TypeMappedAnnotations 对象并返回;
public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>> {
static MergedAnnotations from(Annotation... annotations) {
return from(annotations, annotations);
}
static MergedAnnotations from(Object source, Annotation... annotations) {
return from(source, annotations, RepeatableContainers.standardRepeatables());
}
static MergedAnnotations from(Object source, Annotation[] annotations, RepeatableContainers repeatableContainers) {
return from(source, annotations, repeatableContainers, AnnotationFilter.PLAIN);
}
static MergedAnnotations from(Object source, Annotation[] annotations,
RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
Assert.notNull(repeatableContainers, "RepeatableContainers must not be null");
Assert.notNull(annotationFilter, "AnnotationFilter must not be null");
return TypeMappedAnnotations.from(source, annotations, repeatableContainers, annotationFilter);
}
}
3)SearchStrategy 枚举
SearchStrategy 枚举拥有 5 个不同的元素,DIRECT 标识其搜索策略为只获取对象的直接注解,而不会考虑 @Inherited 注解、超类及实现的接口的注解;INHERITED_ANNOTATIONS 则会考虑直接注解与父类中使用 Inherited 元注解修饰的注解;SUPERCLASS 则会查找所有直接声明和父类注解;TYPE_HIERARCHY 对本类、超类及实现的接口的所有注解进行搜索;最后一个策略为 TYPE_HIERARCHY_AND_ENCLOSING_CLASSES,其用于对本类及其外部类进行全面的搜索,包含本类、超类及实现的接口的所有注解。
public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>> {
enum SearchStrategy {
DIRECT,
INHERITED_ANNOTATIONS,
SUPERCLASS,
TYPE_HIERARCHY,
TYPE_HIERARCHY_AND_ENCLOSING_CLASSES
}
}
1.1.2 of 方法
of 方法则直接利用 annotations 参数执行 MergedAnnotationsCollection 方法的 of 方法创建 MergedAnnotationsCollection 对象并返回;
public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>> {
static MergedAnnotations of(Collection<MergedAnnotation<?>> annotations) {
return MergedAnnotationsCollection.of(annotations);
}
}
1.2 类方法
1.2.1 isPresent 方法
isPresent 方法用于判断指定注解是否直接存在或以元注解的形式存在,MergedAnnotations 接口中定义了两个 isPresent 方法,一个方法直接传入注解类型 class 对象,另一个则传入注解类名;
public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>> {
<A extends Annotation> boolean isPresent(Class<A> annotationType);
boolean isPresent(String annotationType);
}
1.2.2 isDirectlyPresent 方法
isDirectlyPresent 方法用于判断指定注解是否直接存在,MergedAnnotations 接口中也定义了两个 isDirectlyPresent 方法,一个方法直接传入注解类型 class 对象,另一个则传入注解类名;
public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>> {
<A extends Annotation> boolean isDirectlyPresent(Class<A> annotationType);
boolean isDirectlyPresent(String annotationType);
}
1.2.3 get 方法
get 方法用于获取满足指定条件的 annotationType 封装 MergedAnnotation 对象;annotationType 可以直接使用注解对应 Class 对象,也可以使用注解类名;predicate 参数则是查询结果必须满足的条件;selector 参数则是结果使用的选择器。
public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>> {
<A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType);
<A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate);
<A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector);
<A extends Annotation> MergedAnnotation<A> get(String annotationType);
<A extends Annotation> MergedAnnotation<A> get(String annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate);
<A extends Annotation> MergedAnnotation<A> get(String annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector);
}
1.2.4 stream 方法
stream 方法则用于获取指定注解 MergedAnnotation 封装对象流,若方法拥有 annotationType 参数,获取的流关联注解为 annotationType 对应类型,否则获取当前 MergedAnnotations 对象中所有注解流。
public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>> {
<A extends Annotation> Stream<MergedAnnotation<A>> stream(Class<A> annotationType);
<A extends Annotation> Stream<MergedAnnotation<A>> stream(String annotationType);
Stream<MergedAnnotation<Annotation>> stream();
}
2 TypeMappedAnnotations 类
2.1 属性与构造方法
2.1.1 常量
TypeMappedAnnotations 类中只有一个 NONE 常量,用于存储空注解数组封装 TypeMappedAnnotations 对象;
final class TypeMappedAnnotations implements MergedAnnotations {
static final MergedAnnotations NONE = new TypeMappedAnnotations(
null, new Annotation[0], RepeatableContainers.none(), AnnotationFilter.ALL);
}
2.1.2 属性变量
TypeMappedAnnotations 类拥有六个使用 final 关键字进行修饰的属性,用于保存注解源 source、注解修饰元素 element、查询策略 searchStrategy、源注解数组 annotations,Repeatable 元注解处理逻辑 repeatableContainers 及注解查询过滤策略 annotationFilter;除了上述属性之外,还有一个使用 volatile 关键字修饰用于存储注解对象聚合列表的 aggregates 属性
final class TypeMappedAnnotations implements MergedAnnotations {
@Nullable
private final Object source;
@Nullable
private final AnnotatedElement element;
@Nullable
private final SearchStrategy searchStrategy;
@Nullable
private final Annotation[] annotations;
private final RepeatableContainers repeatableContainers;
private final AnnotationFilter annotationFilter;
@Nullable
private volatile List<Aggregate> aggregates;
}
2.1.3 构造方法
TypeMappedAnnotations 类拥有两个构造方法,其中在创建时未传入 source 属性时,则会将 source 属性初始化为 element 参数值,其他属性都是初始化为传入的对应参数,除 source 属性之外所有的未传入属性则会初始化为 null;
final class TypeMappedAnnotations implements MergedAnnotations {
private TypeMappedAnnotations(AnnotatedElement element, SearchStrategy searchStrategy,
RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
this.source = element;
this.element = element;
this.searchStrategy = searchStrategy;
this.annotations = null;
this.repeatableContainers = repeatableContainers;
this.annotationFilter = annotationFilter;
}
private TypeMappedAnnotations(@Nullable Object source, Annotation[] annotations,
RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
this.source = source;
this.element = null;
this.searchStrategy = null;
this.annotations = annotations;
this.repeatableContainers = repeatableContainers;
this.annotationFilter = annotationFilter;
}
}
2.2 静态方法
2.2.1 from 方法
from 静态方法拥有 element 参数时,通过 AnnotationsScanner 类的 isKnownEmpty 判断 element 参数是否拥有满足 searchStrategy 搜索策略参数的注解,若没有则直接返回 NONE 常量值;拥有 annotations 参数时则在其长度为 0 时返回 NONE 常量值,通过上述验证后直接使用入参值创建 TypeMappedAnnotations 对象并返回;
final class TypeMappedAnnotations implements MergedAnnotations {
static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,
RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
if (AnnotationsScanner.isKnownEmpty(element, searchStrategy)) {
return NONE;
}
return new TypeMappedAnnotations(element, searchStrategy, repeatableContainers, annotationFilter);
}
static MergedAnnotations from(@Nullable Object source, Annotation[] annotations,
RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
if (annotations.length == 0) {
return NONE;
}
return new TypeMappedAnnotations(source, annotations, repeatableContainers, annotationFilter);
}
}
2.2.2 isMappingForType 方法
isMappingForType 静态方法是用于判断 mapping 参数关联注解对象是否满足 annotationFilter 参数过滤与是否与 requiredType 相匹配的私有方法;
final class TypeMappedAnnotations implements MergedAnnotations {
private static boolean isMappingForType(AnnotationTypeMapping mapping,
AnnotationFilter annotationFilter, @Nullable Object requiredType) {
Class<? extends Annotation> actualType = mapping.getAnnotationType();
return (!annotationFilter.matches(actualType) &&
(requiredType == null || actualType == requiredType || actualType.getName().equals(requiredType)));
}
}
2.3 Iterable 接口实现
2.3.1 iterator 方法
iterator 方法在 annotationFilter 为 AnnotationFilter.ALL,即过滤对象所有注解时,直接返回 Collections 的 emptyIterator 方法执行结果即空迭代器;否则使用 spliterator 的执行结果调用 Spliterators 的 iterator 方法获取对应注解迭代器;
final class TypeMappedAnnotations implements MergedAnnotations {
@Override
public Iterator<MergedAnnotation<Annotation>> iterator() {
if (this.annotationFilter == AnnotationFilter.ALL) {
return Collections.emptyIterator();
}
return Spliterators.iterator(spliterator());
}
}
2.3.2 spliterator 方法
iterator 方法在 annotationFilter 为 AnnotationFilter.ALL,即过滤对象所有注解时,直接返回 Collections 的 emptySpliterator 方法执行结果即空拆分迭代器;否则使用 null 参数执行私有单参数 spliterator 方法并返回其执行结果;
final class TypeMappedAnnotations implements MergedAnnotations {
@Override
public Spliterator<MergedAnnotation<Annotation>> spliterator() {
if (this.annotationFilter == AnnotationFilter.ALL) {
return Spliterators.emptySpliterator();
}
return spliterator(null);
}
}
单参数 spliterator 方法使用 annotationType 参数值与 getAggregates 方法执行结果创建 AggregatesSpliterator 对象并返回;
final class TypeMappedAnnotations implements MergedAnnotations {
private <A extends Annotation> Spliterator<MergedAnnotation<A>> spliterator(@Nullable Object annotationType) {
return new AggregatesSpliterator<>(annotationType, getAggregates());
}
}
getAggregates 方法在 aggregates 属性为空时,首先尝试将其值初始化为 scan 方法执行结果,若该结果为空或其中没有任何元素时将 aggregates 属性更新为空列表;最后返回该属性值;
final class TypeMappedAnnotations implements MergedAnnotations {
private List<Aggregate> getAggregates() {
List<Aggregate> aggregates = this.aggregates;
if (aggregates == null) {
aggregates = scan(this, new AggregatesCollector());
if (aggregates == null || aggregates.isEmpty()) {
aggregates = Collections.emptyList();
}
this.aggregates = aggregates;
}
return aggregates;
}
}
scan 方法在 annotations 属性不为 null 时,直接调用 processor 参数的 doWithAnnotations 方法获取 List<Aggregate> 对象并调用 processor 的 finish 方法处理 List<Aggregate> 对象并返回执行结果;否则在 element 与 searchStrategy 都不为空时,直接返回 AnnotationsScanner 方法的执行结果;否则直接返回 null;
final class TypeMappedAnnotations implements MergedAnnotations {
@Nullable
private <C, R> R scan(C criteria, AnnotationsProcessor<C, R> processor) {
if (this.annotations != null) {
R result = processor.doWithAnnotations(criteria, 0, this.source, this.annotations);
return processor.finish(result);
}
if (this.element != null && this.searchStrategy != null) {
return AnnotationsScanner.scan(criteria, this.element, this.searchStrategy, processor);
}
return null;
}
}
2.4 MergedAnnotations 接口实现
2.4.1 isPresent 方法
isPresent 方法在 annotationType 与 annotationFilter 过滤器属性匹配时直接返回 false,否则调用 IsPresent 类的 get 方法创建 IsPresent 对象并使用该对象与 annotationType 参数值执行 scan 方法并返回其执行结果,在结果为 null 时返回 false;
final class TypeMappedAnnotations implements MergedAnnotations {
@Override
public <A extends Annotation> boolean isPresent(Class<A> annotationType) {
if (this.annotationFilter.matches(annotationType)) {
return false;
}
return Boolean.TRUE.equals(scan(annotationType,
IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));
}
@Override
public boolean isPresent(String annotationType) {
if (this.annotationFilter.matches(annotationType)) {
return false;
}
return Boolean.TRUE.equals(scan(annotationType,
IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));
}
}
2.4.2 isDirectlyPresent 方法
isDirectlyPresent 方法除了在调用 IsPresent 类的 get 方法的第三个参数为 true 之外,其执行逻辑与 isPresent 方法一致;
final class TypeMappedAnnotations implements MergedAnnotations {
@Override
public <A extends Annotation> boolean isDirectlyPresent(Class<A> annotationType) {
if (this.annotationFilter.matches(annotationType)) {
return false;
}
return Boolean.TRUE.equals(scan(annotationType,
IsPresent.get(this.repeatableContainers, this.annotationFilter, true)));
}
@Override
public boolean isDirectlyPresent(String annotationType) {
if (this.annotationFilter.matches(annotationType)) {
return false;
}
return Boolean.TRUE.equals(scan(annotationType,
IsPresent.get(this.repeatableContainers, this.annotationFilter, true)));
}
}
2.4.3 get 方法
get 方法在 annotationType 与 annotationFilter 过滤器属性匹配时直接返回 MergedAnnotation 类的 missing 方法的执行结果,否则使用 annotationType 与 annotationType、predicate 及 selector 参数创建的 MergedAnnotationFinder 对象执行 scan 方法获取对应的 MergedAnnotation 对象,最后在获取到的对象为 null 时也会直接返回 MergedAnnotation 类的 missing 方法的执行结果,否则直接返回该对象;
final class TypeMappedAnnotations implements MergedAnnotations {
@Override
public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType) {
return get(annotationType, null, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate) {
return get(annotationType, predicate, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector) {
if (this.annotationFilter.matches(annotationType)) {
return MergedAnnotation.missing();
}
MergedAnnotation<A> result = scan(annotationType,
new MergedAnnotationFinder<>(annotationType, predicate, selector));
return (result != null ? result : MergedAnnotation.missing());
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(String annotationType) {
return get(annotationType, null, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(String annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate) {
return get(annotationType, predicate, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(String annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector) {
if (this.annotationFilter.matches(annotationType)) {
return MergedAnnotation.missing();
}
MergedAnnotation<A> result = scan(annotationType,
new MergedAnnotationFinder<>(annotationType, predicate, selector));
return (result != null ? result : MergedAnnotation.missing());
}
}
2.4.4 stream 方法
stream 方法在 annotationFilter 值为 AnnotationFilter.ALL 时直接返回 Stream 的 empty 方法执行结果,即空流;否则使用入参值(在没有入参时使用 null )调用 spliterator 方法并使用该方法执行结果与 false 执行 StreamSupport 的 stream 方法获取对应的 Stream 流对象。
final class TypeMappedAnnotations implements MergedAnnotations {
@Override
public <A extends Annotation> Stream<MergedAnnotation<A>> stream(Class<A> annotationType) {
if (this.annotationFilter == AnnotationFilter.ALL) {
return Stream.empty();
}
return StreamSupport.stream(spliterator(annotationType), false);
}
@Override
public <A extends Annotation> Stream<MergedAnnotation<A>> stream(String annotationType) {
if (this.annotationFilter == AnnotationFilter.ALL) {
return Stream.empty();
}
return StreamSupport.stream(spliterator(annotationType), false);
}
@Override
public Stream<MergedAnnotation<Annotation>> stream() {
if (this.annotationFilter == AnnotationFilter.ALL) {
return Stream.empty();
}
return StreamSupport.stream(spliterator(), false);
}
}
2.5 IsPresent 内部类
2.5.1 属性与构造方法
1)常量
IsPresent 内部类只有一个 IsPresent 数组常量 SHARED,用于缓存常用 IsPresent 处理器对象,避免使用过程中重复创建,其在静态代码块中进行初始化,其拥有 4 个元素,创建时第二个参数都是 AnnotationFilter 类的 PLAIN 常量,第一个参数为 NoRepeatableContainers 或 StandardRepeatableContainers 对象,第三个参数则是 true 或 false;
final class TypeMappedAnnotations implements MergedAnnotations {
private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> {
private static final IsPresent[] SHARED;
static {
SHARED = new IsPresent[4];
SHARED[0] = new IsPresent(RepeatableContainers.none(), AnnotationFilter.PLAIN, true);
SHARED[1] = new IsPresent(RepeatableContainers.none(), AnnotationFilter.PLAIN, false);
SHARED[2] = new IsPresent(RepeatableContainers.standardRepeatables(), AnnotationFilter.PLAIN, true);
SHARED[3] = new IsPresent(RepeatableContainers.standardRepeatables(), AnnotationFilter.PLAIN, false);
}
}
}
2)属性变量
IsPresent 内部类拥有存储 Repeatable 源注解处理逻辑的 repeatableContainers、注解类型过滤器 annotationFilter 及是否只扫描对象直接注解标识的 directOnly 属性;
final class TypeMappedAnnotations implements MergedAnnotations {
private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> {
private final RepeatableContainers repeatableContainers;
private final AnnotationFilter annotationFilter;
private final boolean directOnly;
}
}
3)构造方法
IsPresent 内部类只有一个将属性初始化为指定入参值的构造方法;
final class TypeMappedAnnotations implements MergedAnnotations {
private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> {
private IsPresent(RepeatableContainers repeatableContainers,
AnnotationFilter annotationFilter, boolean directOnly) {
this.repeatableContainers = repeatableContainers;
this.annotationFilter = annotationFilter;
this.directOnly = directOnly;
}
}
}
2.5.2 get 方法
get 方法在 annotationFilter 参数为 AnnotationFilter 的 PLAIN 常量值时,直接通过其余两个参数获取 SHARED 常量中的对应元素对象,否则则使用全参数创建 IsPresent 对象并返回。
final class TypeMappedAnnotations implements MergedAnnotations {
private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> {
static IsPresent get(RepeatableContainers repeatableContainers,
AnnotationFilter annotationFilter, boolean directOnly) {
if (annotationFilter == AnnotationFilter.PLAIN) {
if (repeatableContainers == RepeatableContainers.none()) {
return SHARED[directOnly ? 0 : 1];
}
if (repeatableContainers == RepeatableContainers.standardRepeatables()) {
return SHARED[directOnly ? 2 : 3];
}
}
return new IsPresent(repeatableContainers, annotationFilter, directOnly);
}
}
}
2.5.3 doWithAnnotations 方法
doWithAnnotations 方法对 annotations 参数进行遍历,在元素不为空时且 annotationFilter 参数不会对元素进行过滤时,首先判断该元素是否与 requiredType 参数相匹配,匹配时直接返回 true;随后使用 repeatableContainers 属性的 findRepeatedAnnotations 方法获取 Repeatable 声明的注解对象(StandardRepeatableContainers 对象)或 null(NoRepeatableContainers 对象)然后在结果不为 null 时,使用该值递归执行 doWithAnnotations 方法并在其结果不为 null 时直接返回该结果;最后 directOnly 属性为 false 时,使用该元素的所有非基础元注解递归继续执行 doWithAnnotations 方法并在其结果不为 null 时直接返回该结果;若完成上述遍历但还未返回任何值时直接返回 null。
final class TypeMappedAnnotations implements MergedAnnotations {
private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> {
@Override
@Nullable
public Boolean doWithAnnotations(Object requiredType, int aggregateIndex,
@Nullable Object source, Annotation[] annotations) {
for (Annotation annotation : annotations) {
if (annotation != null) {
Class<? extends Annotation> type = annotation.annotationType();
if (type != null && !this.annotationFilter.matches(type)) {
if (type == requiredType || type.getName().equals(requiredType)) {
return Boolean.TRUE;
}
Annotation[] repeatedAnnotations =
this.repeatableContainers.findRepeatedAnnotations(annotation);
if (repeatedAnnotations != null) {
Boolean result = doWithAnnotations(
requiredType, aggregateIndex, source, repeatedAnnotations);
if (result != null) {
return result;
}
}
if (!this.directOnly) {
AnnotationTypeMappings mappings = AnnotationTypeMappings.forAnnotationType(type);
for (int i = 0; i < mappings.size(); i++) {
AnnotationTypeMapping mapping = mappings.get(i);
if (isMappingForType(mapping, this.annotationFilter, requiredType)) {
return Boolean.TRUE;
}
}
}
}
}
}
return null;
}
}
}
2.6 MergedAnnotationFinder 内部类
2.6.1 属性与构造方法
1)属性变量
MergedAnnotationFinder 内部类用于查询满足指定条件的注解对象,其拥有存储注解类型 class 对象或类名的 requiredType 属性、注解断言的 predicate 属性、注解选择器的 selector 属性及查询结果的 result 属性;
final class TypeMappedAnnotations implements MergedAnnotations {
private class MergedAnnotationFinder<A extends Annotation>
implements AnnotationsProcessor<Object, MergedAnnotation<A>> {
private final Object requiredType;
@Nullable
private final Predicate<? super MergedAnnotation<A>> predicate;
private final MergedAnnotationSelector<A> selector;
@Nullable
private MergedAnnotation<A> result;
}
}
2)构造方法
MergedAnnotationFinder 内部类也只有一个将属性初始化为指定入参值的构造方法,其中值得注意的是在 selector 参数为 null 时,将 selector 属性初始化为 MergedAnnotationSelectors 类的 nearest 方法结果值,否则直接初始化为 selector 参数值;
final class TypeMappedAnnotations implements MergedAnnotations {
private class MergedAnnotationFinder<A extends Annotation>
implements AnnotationsProcessor<Object, MergedAnnotation<A>> {
MergedAnnotationFinder(Object requiredType, @Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector) {
this.requiredType = requiredType;
this.predicate = predicate;
this.selector = (selector != null ? selector : MergedAnnotationSelectors.nearest());
}
}
}
2.6.2 doWithAggregate 方法
doWithAggregate 方法直接返回 result 属性值。
final class TypeMappedAnnotations implements MergedAnnotations {
private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> {
@Override
@Nullable
public MergedAnnotation<A> doWithAggregate(Object context, int aggregateIndex) {
return this.result;
}
}
}
2.6.3 doWithAnnotations 方法
doWithAnnotations 方法对 annotations 参数值进行遍历,在其中元素不为空且 annotationFilter 属性不会过滤该元素时调用 proess 方法处理该对象并在其结果值不为空直接返回该结果,最后遍历完成后直接返回 null。
final class TypeMappedAnnotations implements MergedAnnotations {
private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> {
@Override
@Nullable
public MergedAnnotation<A> doWithAnnotations(Object type, int aggregateIndex,
@Nullable Object source, Annotation[] annotations) {
for (Annotation annotation : annotations) {
if (annotation != null && !annotationFilter.matches(annotation)) {
MergedAnnotation<A> result = process(type, aggregateIndex, source, annotation);
if (result != null) {
return result;
}
}
}
return null;
}
}
}
process 方法首先执行外部对象的 repeatableContainers 属性的 findRepeatedAnnotations 方法并在其结果不为空时直接使用该结果递归执行 doWithAnnotations 方法并返回其结果值,否则使用 AnnotationTypeMappings 的 forAnnotationType 方法创建关联 AnnotationTypeMappings 对象,随后对其遍历,若在元素与 requiredType 属性能匹配时,则使用该元素、source 属性、annotion 参数、aggregateIndex 参数及 IntrospectionFailureLogger 的 INFO 常量值创建 MergedAnnotation 对象并在其不为空且满足 predicate 断言时,若该对象满足 selector 属性的最佳候选对象时直接返回该值,否则只是使用该值执行 updateLastResult 方法;
final class TypeMappedAnnotations implements MergedAnnotations {
private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> {
@Nullable
private MergedAnnotation<A> process(
Object type, int aggregateIndex, @Nullable Object source, Annotation annotation) {
Annotation[] repeatedAnnotations = repeatableContainers.findRepeatedAnnotations(annotation);
if (repeatedAnnotations != null) {
return doWithAnnotations(type, aggregateIndex, source, repeatedAnnotations);
}
AnnotationTypeMappings mappings = AnnotationTypeMappings.forAnnotationType(
annotation.annotationType(), repeatableContainers, annotationFilter);
for (int i = 0; i < mappings.size(); i++) {
AnnotationTypeMapping mapping = mappings.get(i);
if (isMappingForType(mapping, annotationFilter, this.requiredType)) {
MergedAnnotation<A> 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);
}
}
}
return null;
}
}
}
updateLastResult 方法在 result 属性不为空时将 result 属性更新为 result 属性与 candidate 参数执行 selector 属性的 select 方法并返回否则将 result 属性更新为 candidate 参数值;
final class TypeMappedAnnotations implements MergedAnnotations {
private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> {
private void updateLastResult(MergedAnnotation<A> candidate) {
MergedAnnotation<A> lastResult = this.result;
this.result = (lastResult != null ? this.selector.select(lastResult, candidate) : candidate);
}
}
}
2.6.4 finish 方法
finish 方法在 result 参数值不为 null 时直接返回该值,否则返回 result 属性值。
final class TypeMappedAnnotations implements MergedAnnotations {
private static final class IsPresent implements AnnotationsProcessor<Object, Boolean> {
@Override
@Nullable
public MergedAnnotation<A> finish(@Nullable MergedAnnotation<A> result) {
return (result != null ? result : this.result);
}
}
}
2.7 AggregatesCollector 内部类
2.7.1 属性
AggregatesCollector 内部类只有一个用于保存 Aggregate 列表对象的处理结果的 aggregates 属性;
final class TypeMappedAnnotations implements MergedAnnotations {
private class AggregatesCollector implements AnnotationsProcessor<Object, List<Aggregate>> {
private final List<Aggregate> aggregates = new ArrayList<>();
}
}
2.7.2 doWithAnnotations 方法
doWithAnnotations 方法使用入参值执行 createAggregate 方法创建 Aggregate 对象并保存到 aggregates 属性中,最后直接返回 null;
final class TypeMappedAnnotations implements MergedAnnotations {
private class AggregatesCollector implements AnnotationsProcessor<Object, List<Aggregate>> {
@Override
@Nullable
public List<Aggregate> doWithAnnotations(Object criteria, int aggregateIndex,
@Nullable Object source, Annotation[] annotations) {
this.aggregates.add(createAggregate(aggregateIndex, source, annotations));
return null;
}
}
}
createAggregate 方法使用首先利用 annotations 参数执行 getAggregateAnnotations 方法获取注解及满足外部 repeatableContainers 所定义的所有相关注解列表,然后使用处理后的该列表与其余两个参数创建 Aggregate 对象并返回;
final class TypeMappedAnnotations implements MergedAnnotations {
private class AggregatesCollector implements AnnotationsProcessor<Object, List<Aggregate>> {
private Aggregate createAggregate(int aggregateIndex, @Nullable Object source, Annotation[] annotations) {
List<Annotation> aggregateAnnotations = getAggregateAnnotations(annotations);
return new Aggregate(aggregateIndex, source, aggregateAnnotations);
}
}
}
getAggregateAnnotations 方法首先使用 annotations 参数的数组长度创建 Annotation 列表对象,并调用 addAggregateAnnotations 方法将 annotations 参数中的所有值及其关联值全添加到 Annotation 列表对象之后并返回该列表对象;
final class TypeMappedAnnotations implements MergedAnnotations {
private class AggregatesCollector implements AnnotationsProcessor<Object, List<Aggregate>> {
private List<Annotation> getAggregateAnnotations(Annotation[] annotations) {
List<Annotation> result = new ArrayList<>(annotations.length);
addAggregateAnnotations(result, annotations);
return result;
}
}
}
addAggregateAnnotations 方法对 annotations 参数进行遍历,在其元素为 null 或满足 annotationFilter 属性过滤器过滤时直接跳过当次循环,否则使用 repeatableContainers 属性获取该元素的关联注解,在其不为空时递归调用 addAggregateAnnotations 方法将其关联对象添加到 aggregateAnnotations 参数中,否则只是将该元素添加到 aggregateAnnotations 参数中;
final class TypeMappedAnnotations implements MergedAnnotations {
private class AggregatesCollector implements AnnotationsProcessor<Object, List<Aggregate>> {
private void addAggregateAnnotations(List<Annotation> aggregateAnnotations, Annotation[] annotations) {
for (Annotation annotation : annotations) {
if (annotation != null && !annotationFilter.matches(annotation)) {
Annotation[] repeatedAnnotations = repeatableContainers.findRepeatedAnnotations(annotation);
if (repeatedAnnotations != null) {
addAggregateAnnotations(aggregateAnnotations, repeatedAnnotations);
}
else {
aggregateAnnotations.add(annotation);
}
}
}
}
}
}
2.7.3 finish 方法
finish 方法则直接返回 aggregates 属性值;
final class TypeMappedAnnotations implements MergedAnnotations {
private class AggregatesCollector implements AnnotationsProcessor<Object, List<Aggregate>> {
@Override
public List<Aggregate> finish(@Nullable List<Aggregate> processResult) {
return this.aggregates;
}
}
}
2.8 Aggregate 内部类
2.8.1 属性与构造方法
1)属性变量
Aggregate 内部类拥有存储聚合索引的 aggregateIndex 属性、保存源对象的 source 属性、保存全注解列表的 annotations 属性及保存 annotations 属性对应的 AnnotationTypeMappings 对象数组;
final class TypeMappedAnnotations implements MergedAnnotations {
private static class Aggregate {
private final int aggregateIndex;
@Nullable
private final Object source;
private final List<Annotation> annotations;
private final AnnotationTypeMappings[] mappings;
}
}
2)构造方法
Aggregate 内部类在创建过程中首先将 Aggregate、source 及 annotations 属性值初始化为对应参数值,随后将 annotations 属性所有元素转化为对应 AnnotationTypeMappings 对象并保存到 mappings 对应索引处;
final class TypeMappedAnnotations implements MergedAnnotations {
private static class Aggregate {
Aggregate(int aggregateIndex, @Nullable Object source, List<Annotation> annotations) {
this.aggregateIndex = aggregateIndex;
this.source = source;
this.annotations = annotations;
this.mappings = new AnnotationTypeMappings[annotations.size()];
for (int i = 0; i < annotations.size(); i++) {
this.mappings[i] = AnnotationTypeMappings.forAnnotationType(annotations.get(i).annotationType());
}
}
}
}
2.8.2 getMapping 方法
getMapping 方法首先获取 mappings 的 annotationIndex 索引处的 AnnotationTypeMappings 对象,随后如果 AnnotationTypeMappings 对象中存在 mappingIndex 索引元素则直接返回该位置的值否则直接返回 null;
final class TypeMappedAnnotations implements MergedAnnotations {
private static class Aggregate {
@Nullable
AnnotationTypeMapping getMapping(int annotationIndex, int mappingIndex) {
AnnotationTypeMappings mappings = getMappings(annotationIndex);
return (mappingIndex < mappings.size() ? mappings.get(mappingIndex) : null);
}
AnnotationTypeMappings getMappings(int annotationIndex) {
return this.mappings[annotationIndex];
}
}
}
2.8.3 createMergedAnnotationIfPossible 方法
createMergedAnnotationIfPossible 方法直接使用 mappings 属性的 annotationIndex 与 mappingIndex 索引位置值、source 属性值、annotations 属性在 annotationIndex 索引位置对应值、aggregateIndex 属性值及 logger 参数值创建 TypeMappedAnnotation 对象并返回;
final class TypeMappedAnnotations implements MergedAnnotations {
private static class Aggregate {
@Nullable
<A extends Annotation> MergedAnnotation<A> createMergedAnnotationIfPossible(
int annotationIndex, int mappingIndex, IntrospectionFailureLogger logger) {
return TypeMappedAnnotation.createIfPossible(
this.mappings[annotationIndex].get(mappingIndex), this.source,
this.annotations.get(annotationIndex), this.aggregateIndex, logger);
}
}
}
2.9 AggregatesSpliterator 内部类
2.9.1 属性与构造方法
1)属性变量
AggregatesSpliterator 内部类拥有存储需要查找的注解类型的 requiredType 属性、保存使用的 Aggregate 对象列表的 aggregates 属性、保存当前 aggregates 属性已扫描的指针值的 aggregateCursor 属性及保存当前 Aggregate 对象以扫描指针数组;
final class TypeMappedAnnotations implements MergedAnnotations {
private class AggregatesSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
@Nullable
private final Object requiredType;
private final List<Aggregate> aggregates;
private int aggregateCursor;
@Nullable
private int[] mappingCursors;
}
}
2)构造方法
AggregatesSpliterator 内部类在创建过程中在将 requiredType 与 aggregates 属性值初始化为对应参数值并将 aggregateCursor 属性值初始化为 0;
final class TypeMappedAnnotations implements MergedAnnotations {
private class AggregatesSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
AggregatesSpliterator(@Nullable Object requiredType, List<Aggregate> aggregates) {
this.requiredType = requiredType;
this.aggregates = aggregates;
this.aggregateCursor = 0;
}
}
}
2.9.2 tryAdvance 方法
tryAdvance 方法对 aggregates 属性进行遍历,并对其执行私有 tryAdvance 方法,若其执行结果为 true 时直接返回 true,若结果为 false 时将 mappingCursors 属性置为 null,在遍历完后直接返回 false;
final class TypeMappedAnnotations implements MergedAnnotations {
private class AggregatesSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
@Override
public boolean tryAdvance(Consumer<? super MergedAnnotation<A>> action) {
while (this.aggregateCursor < this.aggregates.size()) {
Aggregate aggregate = this.aggregates.get(this.aggregateCursor);
if (tryAdvance(aggregate, action)) {
return true;
}
this.aggregateCursor++;
this.mappingCursors = null;
}
return false;
}
}
}
私有 tryAdvance 方法在 mappingCursors 参数为 null 时将其初始化为 aggregate 参数的大小的 int 类型数组, 随后遍历 aggregate 参数中的所有 AnnotationTypeMapping 对象,将其中与 requiredType 匹配的 AnnotationTypeMapping 对象的 distance 属性值最小的对象所在的 annotationIndex 值更新到 annotationResult 变量中同时将 lowestDistance 变量值更新为 distance 属性值;随后在 annotationResult 变量不等于 -1 时,使用 annotationResult 变量与 mappingCursors 的 annotationResult 索引处的值创建 MergedAnnotation 对象并将 MergedAnnotation 数组的 annotationResult 索引处值加 1;在其为 null 时,则使用 aggregate 参数值与 action 参数值递归调用 tryAdvance 方法并返回其结果值,否则则对该对象执行 action 的 accept 方法并返回 true 否则直接返回 false;
final class TypeMappedAnnotations implements MergedAnnotations {
private class AggregatesSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
private boolean tryAdvance(Aggregate aggregate, Consumer<? super MergedAnnotation<A>> action) {
if (this.mappingCursors == null) {
this.mappingCursors = new int[aggregate.size()];
}
int lowestDistance = Integer.MAX_VALUE;
int annotationResult = -1;
for (int annotationIndex = 0; annotationIndex < aggregate.size(); annotationIndex++) {
AnnotationTypeMapping mapping = getNextSuitableMapping(aggregate, annotationIndex);
if (mapping != null && mapping.getDistance() < lowestDistance) {
annotationResult = annotationIndex;
lowestDistance = mapping.getDistance();
}
if (lowestDistance == 0) {
break;
}
}
if (annotationResult != -1) {
MergedAnnotation<A> mergedAnnotation = aggregate.createMergedAnnotationIfPossible(
annotationResult, this.mappingCursors[annotationResult],
this.requiredType != null ? IntrospectionFailureLogger.INFO : IntrospectionFailureLogger.DEBUG);
this.mappingCursors[annotationResult]++;
if (mergedAnnotation == null) {
return tryAdvance(aggregate, action);
}
action.accept(mergedAnnotation);
return true;
}
return false;
}
}
}
getNextSuitableMapping 方法在 mappingCursors 属性为 null 时直接返回 null,否则使用 annotationIndex 参数与 mappingCursors 属性的 annotationIndex 索引位置的值调用 aggregate 参数的 getMapping 方法获取对应位置处的 AnnotationTypeMapping 对象,并在该值不为 null 且 requiredType 与该对象匹配时直接返回该 AnnotationTypeMapping 对象,否则将对应指针 +1 并继续遍历直到指针值超出了对应 aggregate 参数的对应位置 mappings 元素大小,然后返回 null。
final class TypeMappedAnnotations implements MergedAnnotations {
private class AggregatesSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
@Nullable
private AnnotationTypeMapping getNextSuitableMapping(Aggregate aggregate, int annotationIndex) {
int[] cursors = this.mappingCursors;
if (cursors != null) {
AnnotationTypeMapping mapping;
do {
mapping = aggregate.getMapping(annotationIndex, cursors[annotationIndex]);
if (mapping != null && isMappingForType(mapping, annotationFilter, this.requiredType)) {
return mapping;
}
cursors[annotationIndex]++;
}
while (mapping != null);
}
return null;
}
}
}
3 MergedAnnotationsCollection类
3.1 属性与构造方法
3.1.1 属性变量
MergedAnnotationsCollection 类中拥有两个属性,其中 annotations 属性用于保存处理结果 MergedAnnotation 数组与保存内部 AnnotationTypeMappings 对象数组的 mappings 属性;
final class MergedAnnotationsCollection implements MergedAnnotations {
private final MergedAnnotation<?>[] annotations;
private final AnnotationTypeMappings[] mappings;
}
3.1.2 构造方法
MergedAnnotationsCollection 类只有一个带 MergedAnnotation 对象集合 annotations 参数的构造方法,在对象创建过程中首先对 annotations 参数进行非空断言,通过验证后直接将其转化为 MergedAnnotation 对象数组并将其保存到 annotations 属性值;同时对 annotations 参数中的所有元素非空、元素的 isDirectlyPresent 方法执行结果与 getAggregateIndex 执行结果是否为 0 进行断言判断,即 annotations 参数必须满足不存在 null 元素,所有元素都是直接修饰注解及聚合索引为 0 三个条件;在 annotations 参数通过满足上述条件后,使用 AnnotationTypeMappings 的 forAnnotationType 方法将其所有元素全转换为 AnnotationTypeMappings 对象并将其保存到 mappings 属性中;
final class MergedAnnotationsCollection implements MergedAnnotations {
private MergedAnnotationsCollection(Collection<MergedAnnotation<?>> annotations) {
Assert.notNull(annotations, "Annotations must not be null");
this.annotations = annotations.toArray(new MergedAnnotation<?>[0]);
this.mappings = new AnnotationTypeMappings[this.annotations.length];
for (int i = 0; i < this.annotations.length; i++) {
MergedAnnotation<?> annotation = this.annotations[i];
Assert.notNull(annotation, "Annotation must not be null");
Assert.isTrue(annotation.isDirectlyPresent(), "Annotation must be directly present");
Assert.isTrue(annotation.getAggregateIndex() == 0, "Annotation must have aggregate index of zero");
this.mappings[i] = AnnotationTypeMappings.forAnnotationType(annotation.getType());
}
}
}
3.2 静态方法
3.2.1 of 方法
of 静态方法首先对 annotations 参数进行非空断言,在 annotations 参数没有任何元素时直接返回 TypeMappedAnnotations 类的 NONE 常量值,否则使用 annotations 参数创建本对象并返回;
final class MergedAnnotationsCollection implements MergedAnnotations {
static MergedAnnotations of(Collection<MergedAnnotation<?>> annotations) {
Assert.notNull(annotations, "Annotations must not be null");
if (annotations.isEmpty()) {
return TypeMappedAnnotations.NONE;
}
return new MergedAnnotationsCollection(annotations);
}
}
3.3 Iterable 接口实现
3.3.1 iterator 方法
iterator 方法执行无参 spliterator 方法并使用该结果执行 Spliterators 类的 iterator 方法随后返回执行结果;
final class MergedAnnotationsCollection implements MergedAnnotations {
@Override
public Iterator<MergedAnnotation<Annotation>> iterator() {
return Spliterators.iterator(spliterator());
}
}
3.3.2 spliterator 方法
无参 spliterator 方法直接使用 null 执行私有 spliterator 方法创建 AnnotationsSpliterator 对象并返回;
final class MergedAnnotationsCollection implements MergedAnnotations {
@Override
public Spliterator<MergedAnnotation<Annotation>> spliterator() {
return spliterator(null);
}
private <A extends Annotation> Spliterator<MergedAnnotation<A>> spliterator(@Nullable Object annotationType) {
return new AnnotationsSpliterator<>(annotationType);
}
}
3.4 MergedAnnotations 接口实现
3.4.1 isPresent 方法
isPresent 方法直接使用入参值与 false 执行私有 isPresent 方法并返回其结果;
final class MergedAnnotationsCollection implements MergedAnnotations {
@Override
public <A extends Annotation> boolean isPresent(Class<A> annotationType) {
return isPresent(annotationType, false);
}
@Override
public boolean isPresent(String annotationType) {
return isPresent(annotationType, false);
}
}
私有 isPresent 方法首先查找 annotations 属性中是否存在与 requiredType 参数相匹配的元素,存在时直接返回 true;若 annotations 属性不存在匹配元素且 directOnly 为 true 时直接返回 false,否则查找 mappings 属性中是否存在 isMappingForType 执行结果为 true 的元素,存在时也会返回 true,否则返回 false;
final class MergedAnnotationsCollection implements MergedAnnotations {
private boolean isPresent(Object requiredType, boolean directOnly) {
for (MergedAnnotation<?> annotation : this.annotations) {
Class<? extends Annotation> type = annotation.getType();
if (type == requiredType || type.getName().equals(requiredType)) {
return true;
}
}
if (!directOnly) {
for (AnnotationTypeMappings mappings : this.mappings) {
for (int i = 1; i < mappings.size(); i++) {
AnnotationTypeMapping mapping = mappings.get(i);
if (isMappingForType(mapping, requiredType)) {
return true;
}
}
}
}
return false;
}
}
isMappingForType 方法在 requiredType 参数为 null 时直接返回 true,否则返回 mapping 参数关联注解是否与 requiredType 参数匹配;
final class MergedAnnotationsCollection implements MergedAnnotations {
private static boolean isMappingForType(AnnotationTypeMapping mapping, @Nullable Object requiredType) {
if (requiredType == null) {
return true;
}
Class<? extends Annotation> actualType = mapping.getAnnotationType();
return (actualType == requiredType || actualType.getName().equals(requiredType));
}
}
3.4.2 isDirectlyPresent 方法
isDirectlyPresent 方法直接使用入参值与 true 执行私有 isPresent 方法并返回其结果;
final class MergedAnnotationsCollection implements MergedAnnotations {
@Override
public <A extends Annotation> boolean isDirectlyPresent(Class<A> annotationType) {
return isPresent(annotationType, true);
}
@Override
public boolean isDirectlyPresent(String annotationType) {
return isPresent(annotationType, true);
}
}
3.4.3 get 方法
get 方法直接调用 find 方法并在其不为 null 时直接返回其结果,否则返回 MergedAnnotation 类的 missing 方法执行结果,其传参除 annotationType 必须通过外部传入以外,其余两个参数在未传入时直接传 null;
final class MergedAnnotationsCollection implements MergedAnnotations {
@Override
public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType) {
return get(annotationType, null, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate) {
return get(annotationType, predicate, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector) {
MergedAnnotation<A> result = find(annotationType, predicate, selector);
return (result != null ? result : MergedAnnotation.missing());
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(String annotationType) {
return get(annotationType, null, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(String annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate) {
return get(annotationType, predicate, null);
}
@Override
public <A extends Annotation> MergedAnnotation<A> get(String annotationType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector) {
MergedAnnotation<A> result = find(annotationType, predicate, selector);
return (result != null ? result : MergedAnnotation.missing());
}
}
find 方法在 selector 选择器参数为空时直接使用 Nearest 对象作为其选择器参数,随后获取 annotations 属性中与 requiredType 参数匹配的元素中满足 predicate 断言参数对象其最能最能满足 selector 选择器参数的元素并返回,其中 Nearest 选择器选择层数最低的注解对象元素;
final class MergedAnnotationsCollection implements MergedAnnotations {
@Nullable
private <A extends Annotation> MergedAnnotation<A> find(Object requiredType,
@Nullable Predicate<? super MergedAnnotation<A>> predicate,
@Nullable MergedAnnotationSelector<A> selector) {
if (selector == null) {
selector = MergedAnnotationSelectors.nearest();
}
MergedAnnotation<A> result = null;
for (int i = 0; i < this.annotations.length; i++) {
MergedAnnotation<?> root = this.annotations[i];
AnnotationTypeMappings mappings = this.mappings[i];
for (int mappingIndex = 0; mappingIndex < mappings.size(); mappingIndex++) {
AnnotationTypeMapping mapping = mappings.get(mappingIndex);
if (!isMappingForType(mapping, requiredType)) {
continue;
}
MergedAnnotation<A> candidate = (mappingIndex == 0 ? (MergedAnnotation<A>) root :
TypeMappedAnnotation.createIfPossible(mapping, root, IntrospectionFailureLogger.INFO));
if (candidate != null && (predicate == null || predicate.test(candidate))) {
if (selector.isBestCandidate(candidate)) {
return candidate;
}
result = (result != null ? selector.select(result, candidate) : candidate);
}
}
}
return result;
}
}
3.4.4 stream 方法
stream 使用 spliterator 方法的执行结果与 false 值调用 StreamSupport 类的 stream 方法创建对应流并返回。
final class MergedAnnotationsCollection implements MergedAnnotations {
@Override
public <A extends Annotation> Stream<MergedAnnotation<A>> stream(Class<A> annotationType) {
return StreamSupport.stream(spliterator(annotationType), false);
}
@Override
public <A extends Annotation> Stream<MergedAnnotation<A>> stream(String annotationType) {
return StreamSupport.stream(spliterator(annotationType), false);
}
@Override
public Stream<MergedAnnotation<Annotation>> stream() {
return StreamSupport.stream(spliterator(), false);
}
}
3.5 AnnotationsSpliterator 内部类
3.5.1 属性与构造方法
1)属性变量
AnnotationsSpliterator 内部类拥有用于保存当前需要检索的注解类型的 requiredType 与保存当前 annotations 数组属性对应的搜索指针;
final class MergedAnnotationsCollection implements MergedAnnotations {
private class AnnotationsSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
@Nullable
private Object requiredType;
private final int[] mappingCursors;
}
}
2)构造方法
AnnotationsSpliterator 对象的创建分别将 mappingCursors 与 requiredType 属性初始化为 annotations 属性对应大小的 int 类型数组与传入的 requiredType 参数值;
final class MergedAnnotationsCollection implements MergedAnnotations {
private class AnnotationsSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
public AnnotationsSpliterator(@Nullable Object requiredType) {
this.mappingCursors = new int[annotations.length];
this.requiredType = requiredType;
}
}
}
3.5.2 tryAdvance 方法
tryAdvance 方法首先查询首先获取 annotations 属性与 requiredType 属性匹配且其 distance 属性最小的 AnnotationTypeMapping 对象并使用该对象及其对应的 annotations 属性中的元素创建 TypeMappedAnnotation 对象,且在其为空时直接递归调用 tryAdvance 方法否则使用 action 参数的 accept 方法处理该对象并返回 false;若不满足上述条件时直接返回 false;
final class MergedAnnotationsCollection implements MergedAnnotations {
private class AnnotationsSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
@Override
public boolean tryAdvance(Consumer<? super MergedAnnotation<A>> action) {
int lowestDistance = Integer.MAX_VALUE;
int annotationResult = -1;
for (int annotationIndex = 0; annotationIndex < annotations.length; annotationIndex++) {
AnnotationTypeMapping mapping = getNextSuitableMapping(annotationIndex);
if (mapping != null && mapping.getDistance() < lowestDistance) {
annotationResult = annotationIndex;
lowestDistance = mapping.getDistance();
}
if (lowestDistance == 0) {
break;
}
}
if (annotationResult != -1) {
MergedAnnotation<A> mergedAnnotation = createMergedAnnotationIfPossible(
annotationResult, this.mappingCursors[annotationResult]);
this.mappingCursors[annotationResult]++;
if (mergedAnnotation == null) {
return tryAdvance(action);
}
action.accept(mergedAnnotation);
return true;
}
return false;
}
}
}
getNextSuitableMapping 方法查询 mappings 属性中 annotationIndex 参数对应元素中 mappingCursors 中对应位置指针之后的下一个与 requiredType 属性匹配的注解对象,获取到时直接返回该属性值,否则返回 null;
final class MergedAnnotationsCollection implements MergedAnnotations {
private class AnnotationsSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
@Nullable
private AnnotationTypeMapping getNextSuitableMapping(int annotationIndex) {
AnnotationTypeMapping mapping;
do {
mapping = getMapping(annotationIndex, this.mappingCursors[annotationIndex]);
if (mapping != null && isMappingForType(mapping, this.requiredType)) {
return mapping;
}
this.mappingCursors[annotationIndex]++;
}
while (mapping != null);
return null;
}
}
}
getMapping 方法首先获取 mappings 属性在 annotationIndex 参数处的元素对象并在该元素的大小大于 mappingIndex 参数值时则返回该元素对应元素值否则返回 null;
final class MergedAnnotationsCollection implements MergedAnnotations {
private class AnnotationsSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
@Nullable
private AnnotationTypeMapping getMapping(int annotationIndex, int mappingIndex) {
AnnotationTypeMappings mappings = MergedAnnotationsCollection.this.mappings[annotationIndex];
return (mappingIndex < mappings.size() ? mappings.get(mappingIndex) : null);
}
}
}
createMergedAnnotationIfPossible 方法在 mappingIndex 为 0 时直接返回 annotations 属性 annotationIndex 参数对应索引处的元素值;否则使用 mappings 属性 annotationIndex 参数对应索引处的元素值中 mappingIndex 对应索引处的注解对象与 annotations 属性 annotationIndex 参数对应索引处的元素值创建 TypeMappedAnnotation 对象并返回;
final class MergedAnnotationsCollection implements MergedAnnotations {
private class AnnotationsSpliterator<A extends Annotation> implements Spliterator<MergedAnnotation<A>> {
@Nullable
@SuppressWarnings("unchecked")
private MergedAnnotation<A> createMergedAnnotationIfPossible(int annotationIndex, int mappingIndex) {
MergedAnnotation<?> root = annotations[annotationIndex];
if (mappingIndex == 0) {
return (MergedAnnotation<A>) root;
}
IntrospectionFailureLogger logger = (this.requiredType != null ?
IntrospectionFailureLogger.INFO : IntrospectionFailureLogger.DEBUG);
return TypeMappedAnnotation.createIfPossible(
mappings[annotationIndex].get(mappingIndex), root, logger);
}
}
}
五 MergedAnnotation 对象
MergedAnnotation 为注解封装对象,向外提供注解操作功能,其顶层为 MergedAnnotation 接口,该接口直接实现类只有 AbstractMergedAnnotation 抽象类,该抽象类拥有两个底层类,分别为空注解封装类 MissingMergedAnnotation 与非空注解封装类 TypeMappedAnnotation。
1 MergedAnnotation 接口
1.1 静态方法
MergedAnnotation 接口中的静态方法用于获取指定子类对象;
1.1.1 missing 方法
missing 方法直接使用 MissingMergedAnnotation 类的 getInstance 方法获取单例 MissingMergedAnnotation 对象;
public interface MergedAnnotation<A extends Annotation> {
static <A extends Annotation> MergedAnnotation<A> missing() {
return MissingMergedAnnotation.getInstance();
}
}
1.1.2 from 方法
from 方法直接使用 source 参数或 null 与 annotation 参数执行 TypeMappedAnnotation 类的 from 方法创建 TypeMappedAnnotation 对象并返回;
public interface MergedAnnotation<A extends Annotation> {
static <A extends Annotation> MergedAnnotation<A> from(A annotation) {
return from(null, annotation);
}
static <A extends Annotation> MergedAnnotation<A> from(@Nullable Object source, A annotation) {
return TypeMappedAnnotation.from(source, annotation);
}
}
1.1.3 of 方法
of 方法则是使用 classLoader、source、annotationType 及 attributes 参数执行 TypeMappedAnnotation 类的 of 方法创建 TypeMappedAnnotation 对象并返回;注意除 annotationType 参数以外,其他参数为传入时直接使用 null;
public interface MergedAnnotation<A extends Annotation> {
static <A extends Annotation> MergedAnnotation<A> of(Class<A> annotationType) {
return of(null, annotationType, null);
}
static <A extends Annotation> MergedAnnotation<A> of(
Class<A> annotationType, @Nullable Map<String, ?> attributes) {
return of(null, annotationType, attributes);
}
static <A extends Annotation> MergedAnnotation<A> of(
@Nullable AnnotatedElement source, Class<A> annotationType, @Nullable Map<String, ?> attributes) {
return of(null, source, annotationType, attributes);
}
static <A extends Annotation> MergedAnnotation<A> of(
@Nullable ClassLoader classLoader, @Nullable Object source,
Class<A> annotationType, @Nullable Map<String, ?> attributes) {
return TypeMappedAnnotation.of(classLoader, source, annotationType, attributes);
}
}
1.2 类方法
MergedAnnotation 接口提供了获取注解相关参数值与获取注解属性值的方法;
public interface MergedAnnotation<A extends Annotation> {
Class<A> getType();
boolean isPresent();
boolean isDirectlyPresent();
boolean isMetaPresent();
int getDistance();
int getAggregateIndex();
@Nullable
Object getSource();
@Nullable
MergedAnnotation<?> getMetaSource();
MergedAnnotation<?> getRoot();
List<Class<? extends Annotation>> getMetaTypes();
boolean hasNonDefaultValue(String attributeName);
boolean hasDefaultValue(String attributeName) throws NoSuchElementException;
byte getByte(String attributeName) throws NoSuchElementException;
byte[] getByteArray(String attributeName) throws NoSuchElementException;
boolean getBoolean(String attributeName) throws NoSuchElementException;
boolean[] getBooleanArray(String attributeName) throws NoSuchElementException;
char getChar(String attributeName) throws NoSuchElementException;
char[] getCharArray(String attributeName) throws NoSuchElementException;
short getShort(String attributeName) throws NoSuchElementException;
short[] getShortArray(String attributeName) throws NoSuchElementException;
int getInt(String attributeName) throws NoSuchElementException;
int[] getIntArray(String attributeName) throws NoSuchElementException;
long getLong(String attributeName) throws NoSuchElementException;
long[] getLongArray(String attributeName) throws NoSuchElementException;
double getDouble(String attributeName) throws NoSuchElementException;
double[] getDoubleArray(String attributeName) throws NoSuchElementException;
float getFloat(String attributeName) throws NoSuchElementException;
float[] getFloatArray(String attributeName) throws NoSuchElementException;
String getString(String attributeName) throws NoSuchElementException;
String[] getStringArray(String attributeName) throws NoSuchElementException;
Class<?> getClass(String attributeName) throws NoSuchElementException;
Class<?>[] getClassArray(String attributeName) throws NoSuchElementException;
<E extends Enum<E>> E getEnum(String attributeName, Class<E> type) throws NoSuchElementException;
<E extends Enum<E>> E[] getEnumArray(String attributeName, Class<E> type) throws NoSuchElementException;
<T extends Annotation> MergedAnnotation<T> getAnnotation(String attributeName, Class<T> type)
throws NoSuchElementException;
<T extends Annotation> MergedAnnotation<T>[] getAnnotationArray(String attributeName, Class<T> type)
throws NoSuchElementException;
Optional<Object> getValue(String attributeName);
<T> Optional<T> getValue(String attributeName, Class<T> type);
Optional<Object> getDefaultValue(String attributeName);
<T> Optional<T> getDefaultValue(String attributeName, Class<T> type);
MergedAnnotation<A> filterDefaultValues();
MergedAnnotation<A> filterAttributes(Predicate<String> predicate);
MergedAnnotation<A> withNonMergedAttributes();
AnnotationAttributes asAnnotationAttributes(Adapt... adaptations);
Map<String, Object> asMap(Adapt... adaptations);
<T extends Map<String, Object>> T asMap(Function<MergedAnnotation<?>, T> factory, Adapt... adaptations);
A synthesize() throws NoSuchElementException;
Optional<A> synthesize(Predicate<? super MergedAnnotation<A>> condition) throws NoSuchElementException;
}
1.3 Adapt 内部枚举
Adapt 内部枚举用于标识使用的适配器,其中 CLASS_TO_STRING 使用类或类数组属性适应字符串,ANNOTATION_TO_MAP 则是使用嵌套注释或注释数组适应 Map;
public interface MergedAnnotation<A extends Annotation> {
enum Adapt {
CLASS_TO_STRING,
ANNOTATION_TO_MAP;
protected final boolean isIn(Adapt... adaptations) {
for (Adapt candidate : adaptations) {
if (candidate == this) {
return true;
}
}
return false;
}
public static Adapt[] values(boolean classToString, boolean annotationsToMap) {
EnumSet<Adapt> result = EnumSet.noneOf(Adapt.class);
addIfTrue(result, Adapt.CLASS_TO_STRING, classToString);
addIfTrue(result, Adapt.ANNOTATION_TO_MAP, annotationsToMap);
return result.toArray(new Adapt[0]);
}
private static <T> void addIfTrue(Set<T> result, T value, boolean test) {
if (test) {
result.add(value);
}
}
}
}
2 AbstractMergedAnnotation 抽象类
2.1 属性
AbstractMergedAnnotation 抽象类中只有一个保存同步注解对象的 synthesizedAnnotation 属性;
abstract class AbstractMergedAnnotation<A extends Annotation> implements MergedAnnotation<A> {
@Nullable
private volatile A synthesizedAnnotation;
}
2.2 isPresent 相关方法
AbstractMergedAnnotation 抽象类中实现了两个与 isPresent 相关方法,其中 isDirectlyPresent 与 isMetaPresent 方法分别判断当前注解是否为直接注解或元注解;
abstract class AbstractMergedAnnotation<A extends Annotation> implements MergedAnnotation<A> {
@Override
public boolean isDirectlyPresent() {
return isPresent() && getDistance() == 0;
}
@Override
public boolean isMetaPresent() {
return isPresent() && getDistance() > 0;
}
}
2.3 注解属性方法
hasNonDefaultValue 方法用于判断指定属性是否没有默认值,其直接返回 hasDefaultValue 方法结果的反值;getDefaultValue 方法则是用于获取属性关联默认值,其直接使用 Object 泪对象调用 getDefaultValue 方法并返回执行结果。
abstract class AbstractMergedAnnotation<A extends Annotation> implements MergedAnnotation<A> {
@Override
public boolean hasNonDefaultValue(String attributeName) {
return !hasDefaultValue(attributeName);
}
@Override
public Optional<Object> getDefaultValue(String attributeName) {
return getDefaultValue(attributeName, Object.class);
}
}
属性相关 get 方法对的实现都是直接调用 getRequiredAttributeValue 与 getValue 方法并返回其执行结果;
abstract class AbstractMergedAnnotation<A extends Annotation> implements MergedAnnotation<A> {
@Override
public byte getByte(String attributeName) {
return getRequiredAttributeValue(attributeName, Byte.class);
}
@Override
public byte[] getByteArray(String attributeName) {
return getRequiredAttributeValue(attributeName, byte[].class);
}
@Override
public boolean getBoolean(String attributeName) {
return getRequiredAttributeValue(attributeName, Boolean.class);
}
@Override
public boolean[] getBooleanArray(String attributeName) {
return getRequiredAttributeValue(attributeName, boolean[].class);
}
@Override
public char getChar(String attributeName) {
return getRequiredAttributeValue(attributeName, Character.class);
}
@Override
public char[] getCharArray(String attributeName) {
return getRequiredAttributeValue(attributeName, char[].class);
}
@Override
public short getShort(String attributeName) {
return getRequiredAttributeValue(attributeName, Short.class);
}
@Override
public short[] getShortArray(String attributeName) {
return getRequiredAttributeValue(attributeName, short[].class);
}
@Override
public int getInt(String attributeName) {
return getRequiredAttributeValue(attributeName, Integer.class);
}
@Override
public int[] getIntArray(String attributeName) {
return getRequiredAttributeValue(attributeName, int[].class);
}
@Override
public long getLong(String attributeName) {
return getRequiredAttributeValue(attributeName, Long.class);
}
@Override
public long[] getLongArray(String attributeName) {
return getRequiredAttributeValue(attributeName, long[].class);
}
@Override
public double getDouble(String attributeName) {
return getRequiredAttributeValue(attributeName, Double.class);
}
@Override
public double[] getDoubleArray(String attributeName) {
return getRequiredAttributeValue(attributeName, double[].class);
}
@Override
public float getFloat(String attributeName) {
return getRequiredAttributeValue(attributeName, Float.class);
}
@Override
public float[] getFloatArray(String attributeName) {
return getRequiredAttributeValue(attributeName, float[].class);
}
@Override
public String getString(String attributeName) {
return getRequiredAttributeValue(attributeName, String.class);
}
@Override
public String[] getStringArray(String attributeName) {
return getRequiredAttributeValue(attributeName, String[].class);
}
@Override
public Class<?> getClass(String attributeName) {
return getRequiredAttributeValue(attributeName, Class.class);
}
@Override
public Class<?>[] getClassArray(String attributeName) {
return getRequiredAttributeValue(attributeName, Class[].class);
}
@Override
public <E extends Enum<E>> E getEnum(String attributeName, Class<E> type) {
Assert.notNull(type, "Type must not be null");
return getRequiredAttributeValue(attributeName, type);
}
@Override
@SuppressWarnings("unchecked")
public <E extends Enum<E>> E[] getEnumArray(String attributeName, Class<E> type) {
Assert.notNull(type, "Type must not be null");
Class<?> arrayType = Array.newInstance(type, 0).getClass();
return (E[]) getRequiredAttributeValue(attributeName, arrayType);
}
@Override
public Optional<Object> getValue(String attributeName) {
return getValue(attributeName, Object.class);
}
@Override
public <T> Optional<T> getValue(String attributeName, Class<T> type) {
return Optional.ofNullable(getAttributeValue(attributeName, type));
}
}
filterDefaultValues 方法用于返回所有非默认值属性封装 MergedAnnotation 对象,其直接使用 hasNonDefaultValue 方法执行结果调用 filterAttributes 对象;
abstract class AbstractMergedAnnotation<A extends Annotation> implements MergedAnnotation<A> {
@Override
public AnnotationAttributes asAnnotationAttributes(Adapt... adaptations) {
return asMap(mergedAnnotation -> new AnnotationAttributes(mergedAnnotation.getType()), adaptations);
}
}
getRequiredAttributeValue 方法直接使用对应参数执行 getAttributeValue 方法并在其不为 null 时直接返回该值,否则抛出异常;
abstract class AbstractMergedAnnotation<A extends Annotation> implements MergedAnnotation<A> {
private <T> T getRequiredAttributeValue(String attributeName, Class<T> type) {
T value = getAttributeValue(attributeName, type);
if (value == null) {
throw new NoSuchElementException("No attribute named '" + attributeName +
"' present in merged annotation " + getType().getName());
}
return value;
}
@Nullable
protected abstract <T> T getAttributeValue(String attributeName, Class<T> type);
}
2.4 synthesize 方法
带 condition 参数的 synthesize 方法在 condition 参数的断言结果为真时直接返回无参 condition 方法的执行结果否则返回 null;
abstract class AbstractMergedAnnotation<A extends Annotation> implements MergedAnnotation<A> {
@Override
public Optional<A> synthesize(Predicate<? super MergedAnnotation<A>> condition)
throws NoSuchElementException {
return (condition.test(this) ? Optional.of(synthesize()) : Optional.empty());
}
}
无参 synthesize 方法在 isPresent 结果不为 true,即当前注解不存在时直接抛出异常,否则在 synthesizedAnnotation 属性不为空时将其初始化为 createSynthesized 方法的执行结果并返回该属性值;
abstract class AbstractMergedAnnotation<A extends Annotation> implements MergedAnnotation<A> {
@Override
public A synthesize() {
if (!isPresent()) {
throw new NoSuchElementException("Unable to synthesize missing annotation");
}
A synthesized = this.synthesizedAnnotation;
if (synthesized == null) {
synthesized = createSynthesized();
this.synthesizedAnnotation = synthesized;
}
return synthesized;
}
protected abstract A createSynthesized();
}
3 MissingMergedAnnotation 类
3.1 属性及其构造方法
MissingMergedAnnotation 类中拥有一个保存单例 MissingMergedAnnotation 对象的 INSTANCE 静态变量与一个无参构造方法(getInstance 静态方法用于获取该单例对象);
final class MissingMergedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private static final MissingMergedAnnotation<?> INSTANCE = new MissingMergedAnnotation<>();
private MissingMergedAnnotation() {
}
static <A extends Annotation> MergedAnnotation<A> getInstance() {
return (MergedAnnotation<A>) INSTANCE;
}
}
3.2 类方法
MissingMergedAnnotation 类中拥有非常多直接抛出异常的方法;
final class MissingMergedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
public Class<A> getType() {
throw new NoSuchElementException("Unable to get type for missing annotation");
}
@Override
public boolean hasNonDefaultValue(String attributeName) {
throw new NoSuchElementException(
"Unable to check non-default value for missing annotation");
}
@Override
public boolean hasDefaultValue(String attributeName) {
throw new NoSuchElementException(
"Unable to check default value for missing annotation");
}
@Override
public <T extends Annotation> MergedAnnotation<T> getAnnotation(String attributeName,
Class<T> type) throws NoSuchElementException {
throw new NoSuchElementException(
"Unable to get attribute value for missing annotation");
}
@Override
public <T extends Annotation> MergedAnnotation<T>[] getAnnotationArray(
String attributeName, Class<T> type) throws NoSuchElementException {
throw new NoSuchElementException(
"Unable to get attribute value for missing annotation");
}
@Override
protected <T> T getAttributeValue(String attributeName, Class<T> type) {
throw new NoSuchElementException(
"Unable to get attribute value for missing annotation");
}
@Override
protected A createSynthesized() {
throw new NoSuchElementException("Unable to synthesize missing annotation");
}
}
其他方法则会返回指定默认值;
final class MissingMergedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
public boolean isPresent() {
return false;
}
@Override
@Nullable
public Object getSource() {
return null;
}
@Override
@Nullable
public MergedAnnotation<?> getMetaSource() {
return null;
}
@Override
public MergedAnnotation<?> getRoot() {
return this;
}
@Override
public List<Class<? extends Annotation>> getMetaTypes() {
return Collections.emptyList();
}
@Override
public int getDistance() {
return -1;
}
@Override
public int getAggregateIndex() {
return -1;
}
@Override
public <T> Optional<T> getValue(String attributeName, Class<T> type) {
return Optional.empty();
}
@Override
public <T> Optional<T> getDefaultValue(@Nullable String attributeName, Class<T> type) {
return Optional.empty();
}
@Override
public MergedAnnotation<A> filterAttributes(Predicate<String> predicate) {
return this;
}
@Override
public MergedAnnotation<A> withNonMergedAttributes() {
return this;
}
@Override
public AnnotationAttributes asAnnotationAttributes(Adapt... adaptations) {
return new AnnotationAttributes();
}
@Override
public Map<String, Object> asMap(Adapt... adaptations) {
return Collections.emptyMap();
}
@Override
public <T extends Map<String, Object>> T asMap(Function<MergedAnnotation<?>, T> factory, Adapt... adaptations) {
return factory.apply(this);
}
@Override
public String toString() {
return "(missing)";
}
}
4 TypeMappedAnnotation 类
4.1 属性及其构造方法
4.1.1 静态变量
TypeMappedAnnotation 类只有一个存储基础类型 Class 对象与空对象数组映射的 EMPTY_ARRAYS 常量,其赋值过程在静态代码块之中,其将 boolean、byte、char、double、float、int、long、short 及 String 类型对象与其空数组的映射关系保存到 EMPTY_ARRAYS 常量中;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private static final Map<Class<?>, Object> EMPTY_ARRAYS;
static {
Map<Class<?>, Object> emptyArrays = new HashMap<>();
emptyArrays.put(boolean.class, new boolean[0]);
emptyArrays.put(byte.class, new byte[0]);
emptyArrays.put(char.class, new char[0]);
emptyArrays.put(double.class, new double[0]);
emptyArrays.put(float.class, new float[0]);
emptyArrays.put(int.class, new int[0]);
emptyArrays.put(long.class, new long[0]);
emptyArrays.put(short.class, new short[0]);
emptyArrays.put(String.class, new String[0]);
EMPTY_ARRAYS = Collections.unmodifiableMap(emptyArrays);
}
}
4.1.2 类变量
TypeMappedAnnotation 类有 9 个使用 final 修饰的变量,其中 mapping 属性保存的是 AnnotationTypeMapping 关联注解封装对象、classLoader 属性保存的则是注解使用的类加载器对象、source 属性用于保存注解源对象值、rootAttributes 属性保存的是根注解属性值、valueExtractor 属性为 ValueExtractor value 值提取器对象、aggregateIndex 属性用于保存包含此注解对象的聚合集合的索引、useMergedValues 属性则标识当前注解是否合并注解对象、attributeFilter 属性则保存的是属性过滤器、resolvedRootMirrors 与 resolvedMirrors 属性则分别保存
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private final AnnotationTypeMapping mapping;
@Nullable
private final ClassLoader classLoader;
@Nullable
private final Object source;
@Nullable
private final Object rootAttributes;
private final ValueExtractor valueExtractor;
private final int aggregateIndex;
private final boolean useMergedValues;
@Nullable
private final Predicate<String> attributeFilter;
private final int[] resolvedRootMirrors;
private final int[] resolvedMirrors;
@Override
public int getAggregateIndex() {
return this.aggregateIndex;
}
@Override
@Nullable
public Object getSource() {
return this.source;
}
}
4.1.3 构造方法
TypeMappedAnnotation 类拥有三个构造方法,其中在 useMergedValues 参数未传时将 useMergedValues 属性值初始化为 true,在 attributeFilter 参数未传入时则将直接将 attributeFilter 属性置为 null;在入参中存在 resolvedMirrors 参数时,直接将 resolvedRootMirrors 与 resolvedMirrors 属性分别初始化为对应参数值,否则在 resolvedRootMirrors 为 null 时,将该属性值初始化为 mapping.getRoot().getMirrorSets().resolve 方法执行结果,随后在 getDistance 方法为 0 时则会将 resolvedMirrors 属性初始化为 resolvedRootMirrors 属性值否则将其初始化为 mapping. getMirrorSets(). resolve 方法执行结果;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private TypeMappedAnnotation(AnnotationTypeMapping mapping, @Nullable ClassLoader classLoader,
@Nullable Object source, @Nullable Object rootAttributes, ValueExtractor valueExtractor,
int aggregateIndex) {
this(mapping, classLoader, source, rootAttributes, valueExtractor, aggregateIndex, null);
}
private TypeMappedAnnotation(AnnotationTypeMapping mapping, @Nullable ClassLoader classLoader,
@Nullable Object source, @Nullable Object rootAttributes, ValueExtractor valueExtractor,
int aggregateIndex, @Nullable int[] resolvedRootMirrors) {
this.mapping = mapping;
this.classLoader = classLoader;
this.source = source;
this.rootAttributes = rootAttributes;
this.valueExtractor = valueExtractor;
this.aggregateIndex = aggregateIndex;
this.useMergedValues = true;
this.attributeFilter = null;
this.resolvedRootMirrors = (resolvedRootMirrors != null ? resolvedRootMirrors :
mapping.getRoot().getMirrorSets().resolve(source, rootAttributes, this.valueExtractor));
this.resolvedMirrors = (getDistance() == 0 ? this.resolvedRootMirrors :
mapping.getMirrorSets().resolve(source, this, this::getValueForMirrorResolution));
}
private TypeMappedAnnotation(AnnotationTypeMapping mapping, @Nullable ClassLoader classLoader,
@Nullable Object source, @Nullable Object rootAnnotation, ValueExtractor valueExtractor,
int aggregateIndex, boolean useMergedValues, @Nullable Predicate<String> attributeFilter,
int[] resolvedRootMirrors, int[] resolvedMirrors) {
this.classLoader = classLoader;
this.source = source;
this.rootAttributes = rootAnnotation;
this.valueExtractor = valueExtractor;
this.mapping = mapping;
this.aggregateIndex = aggregateIndex;
this.useMergedValues = useMergedValues;
this.attributeFilter = attributeFilter;
this.resolvedRootMirrors = resolvedRootMirrors;
this.resolvedMirrors = resolvedMirrors;
}
}
4.2 静态方法
4.2.1 from 方法
from 方法首先对 annotation 参数进行非空验证,随后使用 AnnotationTypeMappings 的 forAnnotationType 方法创建 AnnotationTypeMappings 对象并使用其第一个元素、null、source 参数、 annotation 参数、ReflectionUtils 类的 invokeMethod 方法以及 0 创建 TypeMappedAnnotation 对象并返回;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
static <A extends Annotation> MergedAnnotation<A> from(@Nullable Object source, A annotation) {
Assert.notNull(annotation, "Annotation must not be null");
AnnotationTypeMappings mappings = AnnotationTypeMappings.forAnnotationType(annotation.annotationType());
return new TypeMappedAnnotation<>(mappings.get(0), null, source, annotation, ReflectionUtils::invokeMethod, 0);
}
}
4.2.2 of 方法
of 方法首先也会对 annotation 参数进行非空验证,随后也会使用 AnnotationTypeMappings 的 forAnnotationType 方法创建 AnnotationTypeMappings 对象并使用其第一个元素、classLoader 参数、source 参数、attributes 参数、TypeMappedAnnotation 类的 extractFromMap 方法以及 0 创建 TypeMappedAnnotation 对象并返回;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
static <A extends Annotation> MergedAnnotation<A> of(
@Nullable ClassLoader classLoader, @Nullable Object source,
Class<A> annotationType, @Nullable Map<String, ?> attributes) {
Assert.notNull(annotationType, "Annotation type must not be null");
AnnotationTypeMappings mappings = AnnotationTypeMappings.forAnnotationType(annotationType);
return new TypeMappedAnnotation<>(
mappings.get(0), classLoader, source, attributes, TypeMappedAnnotation::extractFromMap, 0);
}
}
4.2.3 createIfPossible 方法
createIfPossible 方法首先在 annotation 参数为 TypeMappedAnnotation 对象时,则使用 mapping 参数、typeMappedAnnotation 的 source 属性、rootAttributes 属性、valueExtractor 属性与 aggregateIndex 属性及 logger 参数执行第三个 createIfPossible 方法并返回,否则使用 mapping 参数、typeMappedAnnotation 的 getSource 结果、synthesize 结果与 getAggregateIndex 结果及 logger 参数执行第二个 createIfPossible 方法并返回;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Nullable
static <A extends Annotation> TypeMappedAnnotation<A> createIfPossible(
AnnotationTypeMapping mapping, MergedAnnotation<?> annotation, IntrospectionFailureLogger logger) {
if (annotation instanceof TypeMappedAnnotation) {
TypeMappedAnnotation<?> typeMappedAnnotation = (TypeMappedAnnotation<?>) annotation;
return createIfPossible(mapping, typeMappedAnnotation.source,
typeMappedAnnotation.rootAttributes,
typeMappedAnnotation.valueExtractor,
typeMappedAnnotation.aggregateIndex, logger);
}
return createIfPossible(mapping, annotation.getSource(), annotation.synthesize(),
annotation.getAggregateIndex(), logger);
}
}
第二个 createIfPossible 方法直接使用入参值与 ReflectionUtils 类的 invokeMethod 方法对象执行第三个 createIfPossible 方法并返回;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Nullable
static <A extends Annotation> TypeMappedAnnotation<A> createIfPossible(
AnnotationTypeMapping mapping, @Nullable Object source, Annotation annotation,
int aggregateIndex, IntrospectionFailureLogger logger) {
return createIfPossible(mapping, source, annotation,
ReflectionUtils::invokeMethod, aggregateIndex, logger);
}
}
第三个 createIfPossible 方法直接尝试使用入参值创建 TypeMappedAnnotation 对象,若未出现任何异常则直接返回创建的对象,否则使用 logger 参数记录错误日志并返回 null 值;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Nullable
private static <A extends Annotation> TypeMappedAnnotation<A> createIfPossible(
AnnotationTypeMapping mapping, @Nullable Object source, @Nullable Object rootAttribute,
ValueExtractor valueExtractor, int aggregateIndex, IntrospectionFailureLogger logger) {
try {
return new TypeMappedAnnotation<>(mapping, null, source, rootAttribute,
valueExtractor, aggregateIndex);
}
catch (Exception ex) {
AnnotationUtils.rethrowAnnotationConfigurationException(ex);
if (logger.isEnabled()) {
String type = mapping.getAnnotationType().getName();
String item = (mapping.getDistance() == 0 ? "annotation " + type :
"meta-annotation " + type + " from " + mapping.getRoot().getAnnotationType().getName());
logger.log("Failed to introspect " + item, source, ex);
}
return null;
}
}
}
4.2.4 extractFromMap 方法
extractFromMap 方法在 map 参数为 null 时直接返回 null 否则获取 map 中 attribute 参数方法名对应值;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Nullable
static Object extractFromMap(Method attribute, @Nullable Object map) {
return (map != null ? ((Map<String, ?>) map).get(attribute.getName()) : null);
}
}
4.3 mapping 相关方法
TypeMappedAnnotation 类的 getType、getMetaTypes 及 getDistance 方法都直接调用 mapping 属性的相应方法并返回其结果值;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
@SuppressWarnings("unchecked")
public Class<A> getType() {
return (Class<A>) this.mapping.getAnnotationType();
}
@Override
public List<Class<? extends Annotation>> getMetaTypes() {
return this.mapping.getMetaTypes();
}
@Override
public int getDistance() {
return this.mapping.getDistance();
}
}
getMetaSource 方法首先调用 mapping 属性的 getSource 方法获取器关联 AnnotationTypeMapping 资源对象,并在其为 null 时直接返回 null,否则使用该值、classLoader、source、
rootAttributes、valueExtractor、aggregateIndex 与 resolvedRootMirrors 属性创建 TypeMappedAnnotation 对象并返回;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
@Nullable
public MergedAnnotation<?> getMetaSource() {
AnnotationTypeMapping metaSourceMapping = this.mapping.getSource();
if (metaSourceMapping == null) {
return null;
}
return new TypeMappedAnnotation<>(metaSourceMapping, this.classLoader, this.source,
this.rootAttributes, this.valueExtractor, this.aggregateIndex, this.resolvedRootMirrors);
}
}
getRoot 方法在 getDistance 方法执行结果为 0 时直接返回当前对象,否则使用 mapping 属性对应的根节点对象、classLoader、source、rootAttributes、valueExtractor、aggregateIndex 与 resolvedRootMirrors 属性创建 TypeMappedAnnotation 对象并返回;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
public MergedAnnotation<?> getRoot() {
if (getDistance() == 0) {
return this;
}
AnnotationTypeMapping rootMapping = this.mapping.getRoot();
return new TypeMappedAnnotation<>(rootMapping, this.classLoader, this.source,
this.rootAttributes, this.valueExtractor, this.aggregateIndex, this.resolvedRootMirrors);
}
}
4.4 isPresent 相关方法
isPresent 方法直接返回 true;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
public boolean isPresent() {
return true;
}
}
4.5 hasDefaultValue 方法
hasDefaultValue 方法首先通过 getAttributeIndex 方法获取 attributeName 参数对应属性索引值,随后使用获取的索引值、true 与 false 值执行 getValue 方法获取对应属性值,最后返回该值是否为 null 或默认值;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
public boolean hasDefaultValue(String attributeName) {
int attributeIndex = getAttributeIndex(attributeName, true);
Object value = getValue(attributeIndex, true, false);
return (value == null || this.mapping.isEquivalentToDefaultValue(attributeIndex, value, this.valueExtractor));
}
}
getAttributeIndex 方法首先对 attributeName 参数进行非空断言,随后在 isFiltered 方法执行结果为 true 时将 attributeIndex 变量更新为 -1 否则将该变量更新为 attributeName 对应 mapping 的属性对应索引值;若 attributeIndex 值为 -1 且 required 参数为 true 时直接抛出异常,否则返回 attributeIndex 值;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private int getAttributeIndex(String attributeName, boolean required) {
Assert.hasText(attributeName, "Attribute name must not be null");
int attributeIndex = (isFiltered(attributeName) ? -1 : this.mapping.getAttributes().indexOf(attributeName));
if (attributeIndex == -1 && required) {
throw new NoSuchElementException("No attribute named '" + attributeName +
"' present in merged annotation " + getType().getName());
}
return attributeIndex;
}
}
isFiltered 方法在 attributeFilter 属性为 null 则返回 false,否则使用该属性的 test 方法对 attributeName 参数进行测试并返回其结果的反值;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private boolean isFiltered(String attributeName) {
if (this.attributeFilter != null) {
return !this.attributeFilter.test(attributeName);
}
return false;
}
}
getValue 方法在 useMergedValues 属性为 true 时,通过 mapping 属性的 getAliasMapping 属性方法获取 attributeIndex 索引对应的别名映射属性对应索引,在 useConventionMapping 参数值为 true 且该值为 -1 时,则尝试通过 mapping 属性的 getConventionMapping 属性方法获取关联注解属性对应索引,在获取到对应索引,即获取到的索引值不为 -1 时,将 attributeIndex 参数与 mapping 局部变量分别更新为获取到的索引值与 mapping 属性的根节点值;随后在 forMirrorResolution 参数值为 false 时,根据 mapping 变量是否为根节点来更新 attributeIndex 参数值,为根节点时,获取 resolvedMirrors 属性的 attributeIndex 索引处的值,不为根节点则获取 resolvedRootMirrors 属性的 attributeIndex 索引处的值;再经过上述过程,若 attributeIndex 参数值为 -1 时直接返回 null;随后 mapping 局部变量为根节点时直接获取对应属性方法执行值或默认值,否则执行 getValueFromMetaAnnotation 方法并返回结果值。
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Nullable
private Object getValue(int attributeIndex, boolean useConventionMapping, boolean forMirrorResolution) {
AnnotationTypeMapping mapping = this.mapping;
if (this.useMergedValues) {
int mappedIndex = this.mapping.getAliasMapping(attributeIndex);
if (mappedIndex == -1 && useConventionMapping) {
mappedIndex = this.mapping.getConventionMapping(attributeIndex);
}
if (mappedIndex != -1) {
mapping = mapping.getRoot();
attributeIndex = mappedIndex;
}
}
if (!forMirrorResolution) {
attributeIndex =
(mapping.getDistance() != 0 ? this.resolvedMirrors : this.resolvedRootMirrors)[attributeIndex];
}
if (attributeIndex == -1) {
return null;
}
if (mapping.getDistance() == 0) {
Method attribute = mapping.getAttributes().get(attributeIndex);
Object result = this.valueExtractor.extract(attribute, this.rootAttributes);
return (result != null ? result : attribute.getDefaultValue());
}
return getValueFromMetaAnnotation(attributeIndex, forMirrorResolution);
}
}
getValueFromMetaAnnotation 在 useMergedValues 属性或 forMirrorResolution 参数为 true 时,尝试使用 mapping 属性的 getMappedAnnotationValue 方法获取元注解对应属性值,在获取的属性值不为 null 时,直接返回该值;否则获取 mapping 属性对象的 attributes 属性 attributeIndex 索引处的对应属性方法并直接使用 mapping 绑定的注解执行该方法获取对应执行结果值并返回。
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Nullable
private Object getValueFromMetaAnnotation(int attributeIndex, boolean forMirrorResolution) {
Object value = null;
if (this.useMergedValues || forMirrorResolution) {
value = this.mapping.getMappedAnnotationValue(attributeIndex, forMirrorResolution);
}
if (value == null) {
Method attribute = this.mapping.getAttributes().get(attributeIndex);
value = ReflectionUtils.invokeMethod(attribute, this.mapping.getAnnotation());
}
return value;
}
}
4.6 getAnnotation 方法
getAnnotation 方法首先也是通过 getAttributeIndex 方法获取 attributeName 参数对应属性索引值并使用该索引获取 mapping 属性中对应索引处的方法对象,并对 type 参数进行非 null 及方法返回值断言,在通过验证后使用 attributeIndex 与 attributeName 参数值执行 getRequiredValue 方法并返回执行结果;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
@SuppressWarnings("unchecked")
public <T extends Annotation> MergedAnnotation<T> getAnnotation(String attributeName, Class<T> type)
throws NoSuchElementException {
int attributeIndex = getAttributeIndex(attributeName, true);
Method attribute = this.mapping.getAttributes().get(attributeIndex);
Assert.notNull(type, "Type must not be null");
Assert.isAssignable(type, attribute.getReturnType(),
() -> "Attribute " + attributeName + " type mismatch:");
return (MergedAnnotation<T>) getRequiredValue(attributeIndex, attributeName);
}
}
getRequiredValue 方法首先尝试 attributeIndex 参数与 Object class 对象执行 getValue 方法获取对应的属性值,在器不为 null 时直接返回该值;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private Object getRequiredValue(int attributeIndex, String attributeName) {
Object value = getValue(attributeIndex, Object.class);
if (value == null) {
throw new NoSuchElementException("No element at attribute index "
+ attributeIndex + " for name " + attributeName);
}
return value;
}
}
getValue 方法尝试使用三参数 getValue 参数获取对应属性值,在未获取到时则获取其默认值,最后使用获取到的属性值、对应的方法及 type 参数执行 adapt 方法并返回其结果;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Nullable
private <T> T getValue(int attributeIndex, Class<T> type) {
Method attribute = this.mapping.getAttributes().get(attributeIndex);
Object value = getValue(attributeIndex, true, false);
if (value == null) {
value = attribute.getDefaultValue();
}
return adapt(attribute, value, type);
}
}
adapt 方法在 value 参数为 null 时直接返回 null;随后分别执行 adaptForAttribute 与 getAdaptType 方法来更新 value 与 type 参数值,并在 value 为 Class 对象且 type 为 String class 对象时直接将 value 参数值更新为 value 对象类名;在 value 为 String 对象且 type 为 Class class 对象时,则将 value 参数值更新为 value 类名对应类;在 value 为 Class 对象数组且 type 为 字符串数组类对象时则将 value 转化为类名字符串数组并保存到 value 值;之后在 value 为字符串数组且 type 为 Class 对象数组时将 value 属性转化为对应的类对象数组并更新 value 参数值;在 value 为 MergedAnnotation 对象且 type 为注解对象时,直接将 value 值更新为 value 的 synthesize 方法执行结果;最后在 value 为 MergedAnnotation 对象数组且 type 为注解对象数组时,将 value 参数值更新为 value 数组中的元素的 synthesize 方法执行结果转化的数组;最后在 type 与 value 参数能对应时直接返回 value 值,否则直接抛出异常;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Nullable
private <T> T adapt(Method attribute, @Nullable Object value, Class<T> type) {
if (value == null) {
return null;
}
value = adaptForAttribute(attribute, value);
type = getAdaptType(attribute, type);
if (value instanceof Class && type == String.class) {
value = ((Class<?>) value).getName();
}
else if (value instanceof String && type == Class.class) {
value = ClassUtils.resolveClassName((String) value, getClassLoader());
}
else if (value instanceof Class[] && type == String[].class) {
Class<?>[] classes = (Class<?>[]) value;
String[] names = new String[classes.length];
for (int i = 0; i < classes.length; i++) {
names[i] = classes[i].getName();
}
value = names;
}
else if (value instanceof String[] && type == Class[].class) {
String[] names = (String[]) value;
Class<?>[] classes = new Class<?>[names.length];
for (int i = 0; i < names.length; i++) {
classes[i] = ClassUtils.resolveClassName(names[i], getClassLoader());
}
value = classes;
}
else if (value instanceof MergedAnnotation && type.isAnnotation()) {
MergedAnnotation<?> annotation = (MergedAnnotation<?>) value;
value = annotation.synthesize();
}
else if (value instanceof MergedAnnotation[] && type.isArray() && type.getComponentType().isAnnotation()) {
MergedAnnotation<?>[] annotations = (MergedAnnotation<?>[]) value;
Object array = Array.newInstance(type.getComponentType(), annotations.length);
for (int i = 0; i < annotations.length; i++) {
Array.set(array, i, annotations[i].synthesize());
}
value = array;
}
if (!type.isInstance(value)) {
throw new IllegalArgumentException("Unable to adapt value of type " +
value.getClass().getName() + " to " + type.getName());
}
return (T) value;
}
}
adaptForAttribute 方法在 attribute 参数的返回值类型为数组但 value 参数不为数组对象时,创建只有单 value 元素的数组并使用 attribute 参数与创建的数组对象递归执行 adaptForAttribute 方法并返回其结果;在 attribute 参数的返回值类型为注解时则使用入参值执行 adaptToMergedAnnotation 方法并返回其执行结果;在 attribute 参数的返回值类型为注解类型数组时,将 value 参数的元素使用 adaptToMergedAnnotation 方法转化为 MergedAnnotation 对象数组并返回;在 attribute 参数的返回值类型为 Class 或 String 且 value 为 String 或 Class 对象时,直接返回 value 值;在 attribute 参数的返回值为数组当 value 为空数组时,直接返回对应类型空数组对象;最后若 attribute 参数的返回值类型与 value 对应时,直接返回 value 值,否则抛出异常;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private Object adaptForAttribute(Method attribute, Object value) {
Class<?> attributeType = ClassUtils.resolvePrimitiveIfNecessary(attribute.getReturnType());
if (attributeType.isArray() && !value.getClass().isArray()) {
Object array = Array.newInstance(value.getClass(), 1);
Array.set(array, 0, value);
return adaptForAttribute(attribute, array);
}
if (attributeType.isAnnotation()) {
return adaptToMergedAnnotation(value, (Class<? extends Annotation>) attributeType);
}
if (attributeType.isArray() && attributeType.getComponentType().isAnnotation()) {
MergedAnnotation<?>[] result = new MergedAnnotation<?>[Array.getLength(value)];
for (int i = 0; i < result.length; i++) {
result[i] = adaptToMergedAnnotation(Array.get(value, i),
(Class<? extends Annotation>) attributeType.getComponentType());
}
return result;
}
if ((attributeType == Class.class && value instanceof String) ||
(attributeType == Class[].class && value instanceof String[]) ||
(attributeType == String.class && value instanceof Class) ||
(attributeType == String[].class && value instanceof Class[])) {
return value;
}
if (attributeType.isArray() && isEmptyObjectArray(value)) {
return emptyArray(attributeType.getComponentType());
}
if (!attributeType.isInstance(value)) {
throw new IllegalStateException("Attribute '" + attribute.getName() +
"' in annotation " + getType().getName() + " should be compatible with " +
attributeType.getName() + " but a " + value.getClass().getName() +
" value was returned");
}
return value;
}
}
adaptToMergedAnnotation 方法在 value 参数为 MergedAnnotation 对象时直接返回 value 值,否则使用 AnnotationTypeMappings 类的 AnnotationTypeMappings 方法创建 annotationType 关联的 AnnotationTypeMapping 对象,并使用该参数创建 TypeMappedAnnotation 对象并返回;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private MergedAnnotation<?> adaptToMergedAnnotation(Object value, Class<? extends Annotation> annotationType) {
if (value instanceof MergedAnnotation) {
return (MergedAnnotation<?>) value;
}
AnnotationTypeMapping mapping = AnnotationTypeMappings.forAnnotationType(annotationType).get(0);
return new TypeMappedAnnotation<>(
mapping, null, this.source, value, getValueExtractor(value), this.aggregateIndex);
}
}
getAdaptType 方法在 type 参数值不为 Object Class 对象时直接返回 type 值,否则在 attribute 参数的返回类型为注解时返回 MergedAnnotation Class 类对象,在 attribute 参数的返回类型为注解类型数组时返回 MergedAnnotation 数组 Class 类对象,否则对返回值执行 ClassUtils 类的 resolvePrimitiveIfNecessary 方法在其为基础类型对象时获取其封装对象否则直接返回原返回值对象并返回;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private <T> Class<T> getAdaptType(Method attribute, Class<T> type) {
if (type != Object.class) {
return type;
}
Class<?> attributeType = attribute.getReturnType();
if (attributeType.isAnnotation()) {
return (Class<T>) MergedAnnotation.class;
}
if (attributeType.isArray() && attributeType.getComponentType().isAnnotation()) {
return (Class<T>) MergedAnnotation[].class;
}
return (Class<T>) ClassUtils.resolvePrimitiveIfNecessary(attributeType);
}
}
4.7 getAnnotationArray 方法
getAnnotationArray 方法首先也是通过 getAttributeIndex 方法获取 attributeName 参数对应属性索引值并使用该索引获取 mapping 属性中对应索引处的方法对象,并对 type 参数进行非 null 、内部元素类及方法返回值断言,在通过验证后使用 attributeIndex 与 attributeName 参数值执行 getRequiredValue 方法并返回执行结果;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
@SuppressWarnings("unchecked")
public <T extends Annotation> MergedAnnotation<T>[] getAnnotationArray(
String attributeName, Class<T> type) throws NoSuchElementException {
int attributeIndex = getAttributeIndex(attributeName, true);
Method attribute = this.mapping.getAttributes().get(attributeIndex);
Class<?> componentType = attribute.getReturnType().getComponentType();
Assert.notNull(type, "Type must not be null");
Assert.notNull(componentType, () -> "Attribute " + attributeName + " is not an array");
Assert.isAssignable(type, componentType, () -> "Attribute " + attributeName + " component type mismatch:");
return (MergedAnnotation<T>[]) getRequiredValue(attributeIndex, attributeName);
}
}
4.8 getDefaultValue 方法
getDefaultValue 方法首先也是通过 getAttributeIndex 方法获取 attributeName 参数对应属性索引值并在其值为 -1 时直接返回空 Optional 对象,否则使用 mapping 属性对应方法对象、该方法对象默认值及 type 参数值执行 adapt 方法并返回执行结果;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
public <T> Optional<T> getDefaultValue(String attributeName, Class<T> type) {
int attributeIndex = getAttributeIndex(attributeName, false);
if (attributeIndex == -1) {
return Optional.empty();
}
Method attribute = this.mapping.getAttributes().get(attributeIndex);
return Optional.ofNullable(adapt(attribute, attribute.getDefaultValue(), type));
}
}
4.9 filterAttributes 方法
filterAttributes 方法在 attributeFilter 属性不为空时直接将其添加到 predicate 参数中,并使用本对象除 attributeFilter 属性之外的属性与 predicate 参数创建 TypeMappedAnnotation 对象并返回;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
public MergedAnnotation<A> filterAttributes(Predicate<String> predicate) {
if (this.attributeFilter != null) {
predicate = this.attributeFilter.and(predicate);
}
return new TypeMappedAnnotation<>(this.mapping, this.classLoader, this.source, this.rootAttributes,
this.valueExtractor, this.aggregateIndex, this.useMergedValues, predicate,
this.resolvedRootMirrors, this.resolvedMirrors);
}
}
4.10 withNonMergedAttributes 方法
withNonMergedAttributes 方法使用本对象除 useMergedValues 属性之外的属性与 false 值创建 TypeMappedAnnotation 对象并返回;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
public MergedAnnotation<A> withNonMergedAttributes() {
return new TypeMappedAnnotation<>(this.mapping, this.classLoader, this.source, this.rootAttributes,
this.valueExtractor, this.aggregateIndex, false, this.attributeFilter,
this.resolvedRootMirrors, this.resolvedMirrors);
}
}
4.11 asMap 方法
asMap 方法首先使用 factory 参数创建 Map 对象,未传入该参数时则直接创建 LinkedHashMap 对象,随后对 mapping 属性的关联属性进行遍历,在其中元素未通过 isFiltered 方法过滤时,将 value 变量值初始化为 null,否则将使用元素索引与 getTypeForMapOptions 方法执行结果值执行的 getValue 方法结果值保存到 value 属性中,随后在 value 值不为 null 时将属性名与 adaptValueForMapOptions 方法执行结果值映射保存到创建的 Map 对象中;在遍历完成后直接返回创建并赋值后的 Map 对象。
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
public Map<String, Object> asMap(Adapt... adaptations) {
return Collections.unmodifiableMap(asMap(mergedAnnotation -> new LinkedHashMap<>(), adaptations));
}
@Override
public <T extends Map<String, Object>> T asMap(Function<MergedAnnotation<?>, T> factory, Adapt... adaptations) {
T map = factory.apply(this);
Assert.state(map != null, "Factory used to create MergedAnnotation Map must not return null");
AttributeMethods attributes = this.mapping.getAttributes();
for (int i = 0; i < attributes.size(); i++) {
Method attribute = attributes.get(i);
Object value = (isFiltered(attribute.getName()) ? null :
getValue(i, getTypeForMapOptions(attribute, adaptations)));
if (value != null) {
map.put(attribute.getName(),
adaptValueForMapOptions(attribute, value, map.getClass(), factory, adaptations));
}
}
return map;
}
}
getTypeForMapOptions 方法在 adaptations 参数包含了 CLASS_TO_STRING 枚举且 attribute 的返回值类型或数组元素类型为 Class 类对象时,在返回值为字符串时返回字符串数组类对象否则返回字符串对象,不满足上述条件时直接返回 Object 类对象;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private Class<?> getTypeForMapOptions(Method attribute, Adapt[] adaptations) {
Class<?> attributeType = attribute.getReturnType();
Class<?> componentType = (attributeType.isArray() ? attributeType.getComponentType() : attributeType);
if (Adapt.CLASS_TO_STRING.isIn(adaptations) && componentType == Class.class) {
return (attributeType.isArray() ? String[].class : String.class);
}
return Object.class;
}
}
adaptValueForMapOptions 方法在 value 参数为 MergedAnnotation 对象时,若 adaptations 参数中拥有 ANNOTATION_TO_MAP 枚举元素时,使用 factory 与 adaptations 参数递归 执行该参数的 annotation 参数的 asMap 方法并返回其执行结果,否则返回 annotation 参数的 synthesize 方法执行结果;在 value 参数为 MergedAnnotation 对象数组时,在 adaptations 参数中拥有 ANNOTATION_TO_MAP 枚举元素时,将 value 参数值的所有元素全转化为对应的 Map 对象数组并返回,否则直接返回 value 参数的深度克隆值;
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
private <T extends Map<String, Object>> Object adaptValueForMapOptions(Method attribute, Object value,
Class<?> mapType, Function<MergedAnnotation<?>, T> factory, Adapt[] adaptations) {
if (value instanceof MergedAnnotation) {
MergedAnnotation<?> annotation = (MergedAnnotation<?>) value;
return (Adapt.ANNOTATION_TO_MAP.isIn(adaptations) ?
annotation.asMap(factory, adaptations) : annotation.synthesize());
}
if (value instanceof MergedAnnotation[]) {
MergedAnnotation<?>[] annotations = (MergedAnnotation<?>[]) value;
if (Adapt.ANNOTATION_TO_MAP.isIn(adaptations)) {
Object result = Array.newInstance(mapType, annotations.length);
for (int i = 0; i < annotations.length; i++) {
Array.set(result, i, annotations[i].asMap(factory, adaptations));
}
return result;
}
Object result = Array.newInstance(
attribute.getReturnType().getComponentType(), annotations.length);
for (int i = 0; i < annotations.length; i++) {
Array.set(result, i, annotations[i].synthesize());
}
return result;
}
return value;
}
}
4.12 createSynthesized 方法
createSynthesized 方法在 rootAttributes 属性值与 getType 方法结果值匹配且 isSynthesizable 方法执行结果为 false 时直接返回 rootAttributes 属性值,否则使用本对象与 getType 方法结果值创建代理对象并返回。
final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
@Override
@SuppressWarnings("unchecked")
protected A createSynthesized() {
if (getType().isInstance(this.rootAttributes) && !isSynthesizable()) {
return (A) this.rootAttributes;
}
return SynthesizedMergedAnnotationInvocationHandler.createProxy(this, getType());
}
private boolean isSynthesizable() {
// Already synthesized?
if (this.rootAttributes instanceof SynthesizedAnnotation) {
return false;
}
return this.mapping.isSynthesizable();
}
}
5 AnnotationTypeMappings 类
5.1 属性及其构造方法
5.1.1 静态变量
AnnotationTypeMappings 类拥有三个静态变量,其中 failureLogger 用于保存类使用的错误日志记录处理对象,standardRepeatablesCache 与 noRepeatablesCache 常量则都是用于缓存 AnnotationFilter 与 Cache 对象映射关系,他们之间的区别在 standardRepeatablesCache 缓存的是 RepeatableContainers.standardRepeatables() 关联 Cache,而 noRepeatablesCache 则用于缓存 RepeatableContainers.none() 相关 Cache;
final class AnnotationTypeMappings {
private static final IntrospectionFailureLogger failureLogger = IntrospectionFailureLogger.DEBUG;
private static final Map<AnnotationFilter, Cache> standardRepeatablesCache = new ConcurrentReferenceHashMap<>();
private static final Map<AnnotationFilter, Cache> noRepeatablesCache = new ConcurrentReferenceHashMap<>();
}
5.1.2 类变量
AnnotationTypeMappings 类拥有三个类属性,其中 repeatableContainers 属性保存的是对象使用的 Repeatable 注解处理容器,filter 属性则用于保存使用的注解过滤器,而 mappings 属性保存的则是解析出的 AnnotationTypeMapping 对象列表;
final class AnnotationTypeMappings {
private final RepeatableContainers repeatableContainers;
private final AnnotationFilter filter;
private final List<AnnotationTypeMapping> mappings;
}
5.1.3 构造方法
AnnotationTypeMappings 只有一个私有构造方法,这意味着外部不能直接使用构造方法创建该对象,而是通过 forAnnotationType 静态方法创建本对象;创建时将 repeatableContainers、filter 及 mappings 分别初始化为 repeatableContainers、filter 参数及空 List 列表对象;随后调用 addAllMappings 方法将 annotationType 参数及其所有关联元注解保存到 mappings 属性中,最后使用 afterAllMappingsSet 对 mappings 属性中所有元素进行后处理;
final class AnnotationTypeMappings {
private AnnotationTypeMappings(RepeatableContainers repeatableContainers,
AnnotationFilter filter, Class<? extends Annotation> annotationType) {
this.repeatableContainers = repeatableContainers;
this.filter = filter;
this.mappings = new ArrayList<>();
addAllMappings(annotationType);
this.mappings.forEach(AnnotationTypeMapping::afterAllMappingsSet);
}
}
1)addAllMappings 方法
addAllMappings 方法目的是解析 annotationType 所有相关注解并将其全部保存到 mappings 属性中;该方法首先调用 addAllMappings 方法将 annotationType 参数封装对象添加到 queue 中,随后获取并移除 queue 变量中的第一个 AnnotationTypeMapping 对象元素,并将其添加到 mappings 属性中同时使用 addMetaAnnotationsToQueue 方法将其所有符合条件的元注解添加到 queue 尾部,并在之后对其进行处理值到 annotationType 参数所有关联元注解对象;
final class AnnotationTypeMappings {
private void addAllMappings(Class<? extends Annotation> annotationType) {
Deque<AnnotationTypeMapping> queue = new ArrayDeque<>();
addIfPossible(queue, null, annotationType, null);
while (!queue.isEmpty()) {
AnnotationTypeMapping mapping = queue.removeFirst();
this.mappings.add(mapping);
addMetaAnnotationsToQueue(queue, mapping);
}
}
}
addMetaAnnotationsToQueue 方法对 source 参数关联的注解的所有元注解进行遍历,在元素是不可映射时直接跳过处理该元素;否则使用 repeatableContainers 属性值获取元素对应的注解数组且在该结果为 null 时直接使用 queue、source 及元素执行 addIfPossible 方法将其添加到 queue 参数中,否则执行 addIfPossible 方法将注解数组中可映射元素添加到 queue 参数中;
final class AnnotationTypeMappings {
private void addMetaAnnotationsToQueue(Deque<AnnotationTypeMapping> queue, AnnotationTypeMapping source) {
Annotation[] metaAnnotations = AnnotationsScanner.getDeclaredAnnotations(source.getAnnotationType(), false);
for (Annotation metaAnnotation : metaAnnotations) {
if (!isMappable(source, metaAnnotation)) {
continue;
}
Annotation[] repeatedAnnotations = this.repeatableContainers.findRepeatedAnnotations(metaAnnotation);
if (repeatedAnnotations != null) {
for (Annotation repeatedAnnotation : repeatedAnnotations) {
if (!isMappable(source, repeatedAnnotation)) {
continue;
}
addIfPossible(queue, source, repeatedAnnotation);
}
}
else {
addIfPossible(queue, source, metaAnnotation);
}
}
}
}
isMappable 方法用于判断 metaAnnotation 参数是否不会被 filter 属性与 AnnotationFilter.PLAIN 常量进行过滤且是否已解析过同类型注解元数据;
final class AnnotationTypeMappings {
private boolean isMappable(AnnotationTypeMapping source, @Nullable Annotation metaAnnotation) {
return (metaAnnotation != null && !this.filter.matches(metaAnnotation) &&
!AnnotationFilter.PLAIN.matches(source.getAnnotationType()) &&
!isAlreadyMapped(source, metaAnnotation));
}
private boolean isAlreadyMapped(AnnotationTypeMapping source, Annotation metaAnnotation) {
Class<? extends Annotation> annotationType = metaAnnotation.annotationType();
AnnotationTypeMapping mapping = source;
while (mapping != null) {
if (mapping.getAnnotationType() == annotationType) {
return true;
}
mapping = mapping.getSource();
}
return false;
}
}
addIfPossible 方法直接使用 source、annotationType 与 ann 参数创建 AnnotationTypeMapping 对象并将其添加到 queue 参数的尾端,若出现了任何异常则直接使用 failureLogger 属性处理异常;
final class AnnotationTypeMappings {
private void addIfPossible(Deque<AnnotationTypeMapping> queue, AnnotationTypeMapping source, Annotation ann) {
addIfPossible(queue, source, ann.annotationType(), ann);
}
private void addIfPossible(Deque<AnnotationTypeMapping> queue, @Nullable AnnotationTypeMapping source,
Class<? extends Annotation> annotationType, @Nullable Annotation ann) {
try {
queue.addLast(new AnnotationTypeMapping(source, annotationType, ann));
}
catch (Exception ex) {
AnnotationUtils.rethrowAnnotationConfigurationException(ex);
if (failureLogger.isEnabled()) {
failureLogger.log("Failed to introspect meta-annotation " + annotationType.getName(),
(source != null ? source.getAnnotationType() : null), ex);
}
}
}
}
5.2 静态方法
5.2.1 forAnnotationType 方法
forAnnotationType 方法拥有关联注解元数据类型 annotationType、注解过滤器对象 annotationFilter 及 Repeatable 注解处理容器对象 repeatableContainers 三个参数; annotationType 参数是必须传入的,repeatableContainers 与 annotationFilter 参数未传入时分别默认传入 RepeatableContainers.standardRepeatables() 与 AnnotationFilter.PLAIN 值;在方法执行过程中首先会根据 repeatableContainers 参数值从缓存常量中创建并获取 AnnotationTypeMappings 对象并返回,在 RepeatableContainers 参数为 RepeatableContainers.standardRepeatables() 结果值时,则会从 standardRepeatablesCache 常量中获取对应 AnnotationTypeMappings 对象,等于 RepeatableContainers.none() 结果值时则从 noRepeatablesCache 常量中获取对象并返回;若该参数不满足上述两条件时直接使用全部入参创建 AnnotationTypeMappings 对象并返回。
final class AnnotationTypeMappings {
static AnnotationTypeMappings forAnnotationType(Class<? extends Annotation> annotationType) {
return forAnnotationType(annotationType, AnnotationFilter.PLAIN);
}
static AnnotationTypeMappings forAnnotationType(
Class<? extends Annotation> annotationType, AnnotationFilter annotationFilter) {
return forAnnotationType(annotationType, RepeatableContainers.standardRepeatables(), annotationFilter);
}
static AnnotationTypeMappings forAnnotationType(Class<? extends Annotation> annotationType,
RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
if (repeatableContainers == RepeatableContainers.standardRepeatables()) {
return standardRepeatablesCache.computeIfAbsent(annotationFilter,
key -> new Cache(repeatableContainers, key)).get(annotationType);
}
if (repeatableContainers == RepeatableContainers.none()) {
return noRepeatablesCache.computeIfAbsent(annotationFilter,
key -> new Cache(repeatableContainers, key)).get(annotationType);
}
return new AnnotationTypeMappings(repeatableContainers, annotationFilter, annotationType);
}
}
5.2.2 clearCache 方法
clearCache 方法直接将 standardRepeatablesCache 与 noRepeatablesCache 缓存常量内容清空。
final class AnnotationTypeMappings {
static void clearCache() {
standardRepeatablesCache.clear();
noRepeatablesCache.clear();
}
}
5.3 类方法
size 与 get 两个方法都是直接调用 mappings 属性的对应方法并返回其执行结果。
final class AnnotationTypeMappings {
int size() {
return this.mappings.size();
}
AnnotationTypeMapping get(int index) {
return this.mappings.get(index);
}
}
5.4 Cache 静态内部类
5.4.1 属性与构造方法
Cache 内部类拥有保存 Repeatable 注解处理容器对象的 repeatableContainers 属性、保存注解过滤器对象的 filter 属性及保存已缓存的注解 class 类对象与 AnnotationTypeMappings 对象映射关系;其构造方法中直接将 repeatableContainers 与 filter 属性值初始化为对应入参值,同时将 mappings 属性值初始化为空 ConcurrentReferenceHashMap 对象。
final class AnnotationTypeMappings {
private static class Cache {
private final RepeatableContainers repeatableContainers;
private final AnnotationFilter filter;
private final Map<Class<? extends Annotation>, AnnotationTypeMappings> mappings;
Cache(RepeatableContainers repeatableContainers, AnnotationFilter filter) {
this.repeatableContainers = repeatableContainers;
this.filter = filter;
this.mappings = new ConcurrentReferenceHashMap<>();
}
}
}
5.4.2 get 方法
get 方法直接调用 mappings 属性的 computeIfAbsent 方法获取 annotationType 参数对应的 AnnotationTypeMappings 对象,在对应缓存不存在时,则会调用 createMappings 方法创建该对象并保存 mappings 映射中同时返回。
final class AnnotationTypeMappings {
private static class Cache {
AnnotationTypeMappings get(Class<? extends Annotation> annotationType) {
return this.mappings.computeIfAbsent(annotationType, this::createMappings);
}
}
}
5.4.3 createMappings 方法
createMappings 方法使用 repeatableContainers、filter 属性及 annotationType 参数创建 AnnotationTypeMappings 对象并返回。
final class AnnotationTypeMappings {
private static class Cache {
AnnotationTypeMappings createMappings(Class<? extends Annotation> annotationType) {
return new AnnotationTypeMappings(this.repeatableContainers, this.filter, annotationType);
}
}
}
6 AnnotationTypeMapping 类
6.1 属性及其构造方法
6.1.1 静态变量
AnnotationTypeMapping 类只有一个用于保存空 MirrorSet 对象数组的 EMPTY_MIRROR_SETS 常量;
final class AnnotationTypeMapping {
private static final MirrorSet[] EMPTY_MIRROR_SETS = new MirrorSet[0];
}
6.1.2 属性变量
AnnotationTypeMapping 类中的 source 与 root 属性分别用于保存当前关联的上级注解封装对象与根注解封装对象,distance 属性值为当前封装对象深度,annotationType、metaTypes 以及 annotation 属性分别保存的是关联注解 Class 对象、其元注解列表及实际注解对象,attributes 属性为当前注解所有属性方法对象,mirrorSets 属性保存当前属性解析出来的关联 MirrorSets 对象;aliasMappings 属性则是保存当前方法与根节点中以当前对应位置属性方法对象作为别名的索引对应关系;conventionMappings 保存属性根节点同名属性索引值;annotationValueMappings 属性保存的时属性等效执行的属性索引;annotationValueSource 属性保存的则是 annotationValueMappings 属性对应位置的源 AnnotationTypeMapping 对象;aliasedBy 属性用于保存当前注解中的 AliasFor 注解修饰的属性方法解析结果,其 key 为 AliasFor 注解设置的目标方法对象(可以不为当前当前注解中的属性方法),而映射值则为本注解中 key 对应的属性方法对象列表;synthesizable 属性标识当前对象是否完成同步,claimedAliases 属性保存的则是当前注解及其所有源注解中的 aliasedBy 属性中所有以当前注解属性方法作为 key 的属性方法对象 set 集合(包含 aliasedBy 属性 key 值)。
final class AnnotationTypeMapping {
@Nullable
private final AnnotationTypeMapping source;
private final AnnotationTypeMapping root;
private final int distance;
private final Class<? extends Annotation> annotationType;
private final List<Class<? extends Annotation>> metaTypes;
@Nullable
private final Annotation annotation;
private final AttributeMethods attributes;
private final MirrorSets mirrorSets;
private final int[] aliasMappings;
private final int[] conventionMappings;
private final int[] annotationValueMappings;
private final AnnotationTypeMapping[] annotationValueSource;
private final Map<Method, List<Method>> aliasedBy;
private final boolean synthesizable;
private final Set<Method> claimedAliases = new HashSet<>();
AnnotationTypeMapping getRoot() {
return this.root;
}
@Nullable
AnnotationTypeMapping getSource() {
return this.source;
}
int getDistance() {
return this.distance;
}
Class<? extends Annotation> getAnnotationType() {
return this.annotationType;
}
List<Class<? extends Annotation>> getMetaTypes() {
return this.metaTypes;
}
@Nullable
Annotation getAnnotation() {
return this.annotation;
}
AttributeMethods getAttributes() {
return this.attributes;
}
MirrorSets getMirrorSets() {
return this.mirrorSets;
}
boolean isSynthesizable() {
return this.synthesizable;
}
}
6.1.3 构造方法
AnnotationTypeMapping 类构造方法首先将 source、annotationType 与 annotation 属性分别初始化为 source、annotationType 与 annotation 参数值;随后在 source 参数不为 null 时,分别将 root、distance 与 metaTypes 初始化为 source 参数的 getRoot 方法执行结果、getDistance 方法执行结果 + 1、使用 source 参数的 getMetaTypes 方法执行结果与 annotationType 参数执行 merge 方法结果,否则分别会初始化为 null、0 及 null 与 annotationType 参数执行 merge 方法结果;之后将 attributes 属性初始化为 AttributeMethods 类的 forAnnotationType 方法的执行结果值,同时将 aliasMappings、conventionMappings 及 annotationValueSource 属性通过 filledIntArray 方法初始化为 attributes 属性大小且元素值全为的 -1 的 int 数组;之后将 mirrorSets 属性初始化为 MirrorSets 对象、将 annotationValueSource 属性值初始化为 attributes 属性大小的空 AnnotationTypeMapping 对象数组以及将 aliasedBy 属性初始化为 resolveAliasedForTargets 方法执行结果;最后依次使用 processAliases、addConventionMappings 与 addConventionAnnotationValues 方法进一步处理 aliasMappings、conventionMappings 及 annotationValueSource 属性值并在最后一步使用 computeSynthesizableFlag 方法执行结果为 synthesizable 属性进行赋值;
final class AnnotationTypeMapping {
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();
this.synthesizable = computeSynthesizableFlag();
}
private static int[] filledIntArray(int size) {
int[] array = new int[size];
Arrays.fill(array, -1);
return array;
}
}
1)merge 方法
merge 方法在 existing 方法为空时直接使用 element 参数创建单元素 List 列表对象并返回,否则将 element 参数值添加到 existing 列表参数之后并将其转化为只读 List 列表对象并返回;
final class AnnotationTypeMappings {
private static <T> List<T> merge(@Nullable List<T> existing, T element) {
if (existing == null) {
return Collections.singletonList(element);
}
List<T> merged = new ArrayList<>(existing.size() + 1);
merged.addAll(existing);
merged.add(element);
return Collections.unmodifiableList(merged);
}
}
2)resolveAliasedForTargets 方法
resolveAliasedForTargets 方法获取 attributes 属性中所有使用 AliasFor 注解修饰的元素并将其保存到别名方法对象与属性方法对象映射 aliasedBy 变量中,最后在别名映射完成后将其该映射转换为只读 Map 对象并返回;
final class AnnotationTypeMappings {
private Map<Method, List<Method>> resolveAliasedForTargets() {
Map<Method, List<Method>> aliasedBy = new HashMap<>();
for (int i = 0; i < this.attributes.size(); i++) {
Method attribute = this.attributes.get(i);
AliasFor aliasFor = AnnotationsScanner.getDeclaredAnnotation(attribute, AliasFor.class);
if (aliasFor != null) {
Method target = resolveAliasTarget(attribute, aliasFor);
aliasedBy.computeIfAbsent(target, key -> new ArrayList<>()).add(attribute);
}
}
return Collections.unmodifiableMap(aliasedBy);
}
}
resolveAliasTarget 方法在 aliasFor 参数的 value 与 attribute 属性值都不为空时抛出异常,即 aliasFor 参数的只能存在 value 与 attribute 两个属性中的一个;在通过验证后,使用 aliasFor 参数的 annotation 方法执行结果值保存到 targetAnnotation 局部变量中,在其值为 Annotation 类对象时则将该值更新为 annotationType 属性值;随后将 aliasFor 注解中 attribute 与 value 两属性中不为空的值保存到 targetAttributeName 变量中,若上述两个属性都为空时则将 attribute 方法名保存到该变量中;随后将 target 变量更新为 targetAnnotation 注解名为 targetAttributeName 的属性方法对象并在其为 null 时直接抛出异常,否则若该对象与 attribute 参数相等也会抛出异常,同时在其与 target 参数方法的返回值不一致且不为其内部属性时也会抛出异常;最后在 target 变量是 annotationType 属性中的属性方法且 checkAliasPair 参数为 true 时,继续尝试获取该变量的 AliasFor 注解对象并在其不为 null 时递归调用 resolveAliasTarget 方法获取其镜像方法并在获取到的镜像不等于 attribute 参数时也会直接抛出异常,最后经过了上述验证过程时直接返回 target 变量值;
final class AnnotationTypeMappings {
private Method resolveAliasTarget(Method attribute, AliasFor aliasFor) {
return resolveAliasTarget(attribute, aliasFor, true);
}
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()));
}
Class<? extends Annotation> targetAnnotation = aliasFor.annotation();
if (targetAnnotation == Annotation.class) {
targetAnnotation = this.annotationType;
}
String targetAttributeName = aliasFor.attribute();
if (!StringUtils.hasLength(targetAttributeName)) {
targetAttributeName = aliasFor.value();
}
if (!StringUtils.hasLength(targetAttributeName)) {
targetAttributeName = attribute.getName();
}
Method target = AttributeMethods.forAnnotationType(targetAnnotation).get(targetAttributeName);
if (target == null) {
if (targetAnnotation == this.annotationType) {
throw new AnnotationConfigurationException(String.format(
"@AliasFor declaration on %s declares an alias for '%s' which is not present.",
AttributeMethods.describe(attribute), targetAttributeName));
}
throw new AnnotationConfigurationException(String.format(
"%s is declared as an @AliasFor nonexistent %s.",
StringUtils.capitalize(AttributeMethods.describe(attribute)),
AttributeMethods.describe(targetAnnotation, targetAttributeName)));
}
if (target.equals(attribute)) {
throw new AnnotationConfigurationException(String.format(
"@AliasFor declaration on %s points to itself. " +
"Specify 'annotation' to point to a same-named attribute on a meta-annotation.",
AttributeMethods.describe(attribute)));
}
if (!isCompatibleReturnType(attribute.getReturnType(), target.getReturnType())) {
throw new AnnotationConfigurationException(String.format(
"Misconfigured aliases: %s and %s must declare the same return type.",
AttributeMethods.describe(attribute),
AttributeMethods.describe(target)));
}
if (isAliasPair(target) && checkAliasPair) {
AliasFor targetAliasFor = target.getAnnotation(AliasFor.class);
if (targetAliasFor != null) {
Method mirror = resolveAliasTarget(target, targetAliasFor, false);
if (!mirror.equals(attribute)) {
throw new AnnotationConfigurationException(String.format(
"%s must be declared as an @AliasFor %s, not %s.",
StringUtils.capitalize(AttributeMethods.describe(target)),
AttributeMethods.describe(attribute), AttributeMethods.describe(mirror)));
}
}
}
return target;
}
private boolean isAliasPair(Method target) {
return (this.annotationType == target.getDeclaringClass());
}
private boolean isCompatibleReturnType(Class<?> attributeType, Class<?> targetType) {
return (attributeType == targetType || attributeType == targetType.getComponentType());
}
}
3)processAliases 方法
processAliases 方法对 attributes 属性方法对象进行遍历,将遍历元素及其所有父类中以该元素作为 aliasedBy 属性的 key 的所有属性方法对象保存到 aliases 变量中,并在下次循环开始前清空该变量;之后在 aliases 变量不为空时则会继续使用 processAliases 方法对别名进行处理;
final class AnnotationTypeMappings {
private void processAliases() {
List<Method> 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);
}
}
}
private void collectAliases(List<Method> aliases) {
AnnotationTypeMapping mapping = this;
while (mapping != null) {
int size = aliases.size();
for (int j = 0; j < size; j++) {
List<Method> additional = mapping.aliasedBy.get(aliases.get(j));
if (additional != null) {
aliases.addAll(additional);
}
}
mapping = mapping.source;
}
}
}
processAliases 方法首先通过 getFirstRootAttributeIndex 方法获取根节点第一个包含于 aliases 参数中的第一个元素索引,即根节点中映射到当前属性的别名方法或本方法本身索引值,并保存到 rootAttributeIndex 变量中;随后从本对象向顶层进行遍历,若遍历对象不为 root 根节点且 rootAttributeIndex 变量不为 -1 时,若变量对象的某个属性方法对象包含于 aliases 参数中,则将该对象的 aliasMappings 属性对应索引处值更新为 rootAttributeIndex 变量值,即通过 aliasMappings 属性将根节点属性方法对象与别名相关属性方法对象关联;在遍历完成时后使用 aliases 参数分别执行遍历对象的 mirrorSets 属性的 updateFrom 方法更新 mirrorSets 属性与 claimedAliases 属性的 addAll 方法;最后若遍历对象关联注解对象不为空时,使用遍历对象的 mirrorSets 属性的 resolve 方法获取实际结果值索引数组,并将 annotationValueMappings 与 annotationValueSource 属性包含在 aliases 参数中的属性方法索引处的对应值分别更新为实际属性方法对象索引与当前遍历对象;
final class AnnotationTypeMappings {
private void processAliases(int attributeIndex, List<Method> aliases) {
int rootAttributeIndex = getFirstRootAttributeIndex(aliases);
AnnotationTypeMapping mapping = this;
while (mapping != null) {
if (rootAttributeIndex != -1 && mapping != this.root) {
for (int i = 0; i < mapping.attributes.size(); i++) {
if (aliases.contains(mapping.attributes.get(i))) {
mapping.aliasMappings[i] = rootAttributeIndex;
}
}
}
mapping.mirrorSets.updateFrom(aliases);
mapping.claimedAliases.addAll(aliases);
if (mapping.annotation != null) {
int[] resolvedMirrors = mapping.mirrorSets.resolve(null,
mapping.annotation, ReflectionUtils::invokeMethod);
for (int i = 0; i < mapping.attributes.size(); i++) {
if (aliases.contains(mapping.attributes.get(i))) {
this.annotationValueMappings[attributeIndex] = resolvedMirrors[i];
this.annotationValueSource[attributeIndex] = mapping;
}
}
}
mapping = mapping.source;
}
}
}
getFirstRootAttributeIndex 方法获取根节点的第一个包含在 aliases 参数的第一个元素的索引值,未查询到时直接返回 -1;
final class AnnotationTypeMappings {
private int getFirstRootAttributeIndex(Collection<Method> aliases) {
AttributeMethods rootAttributes = this.root.getAttributes();
for (int i = 0; i < rootAttributes.size(); i++) {
if (aliases.contains(rootAttributes.get(i))) {
return i;
}
}
return -1;
}
}
3)addConventionMappings 方法
addConventionMappings 方法在当前对象为根节点时直接返回,否则对 conventionMappings 属性进行遍历,遍历过程中首先根节点与 attributes 属性对应索引处的属性的同名属性索引值与 mirrorSets 属性中 assigned 对应索引处的 MirrorSet 对象;并在同名索引值不为 -1 且方法名不为 value 时且在对应 MirrorSet 对象不为空时,MirrorSet 对象关联索引处的所有元素值更新为根节点的同名属性索引值;
final class AnnotationTypeMappings {
private void addConventionMappings() {
if (this.distance == 0) {
return;
}
AttributeMethods rootAttributes = this.root.getAttributes();
int[] mappings = this.conventionMappings;
for (int i = 0; i < mappings.length; i++) {
String name = this.attributes.get(i).getName();
MirrorSet mirrors = getMirrorSets().getAssigned(i);
int mapped = rootAttributes.indexOf(name);
if (!MergedAnnotation.VALUE.equals(name) && mapped != -1) {
mappings[i] = mapped;
if (mirrors != null) {
for (int j = 0; j < mirrors.size(); j++) {
mappings[mirrors.getAttributeIndex(j)] = mapped;
}
}
}
}
}
}
4)addConventionAnnotationValues 方法
addConventionAnnotationValues 方法对 attributes 属性的所有元素进行遍历,然后从当前 AnnotationTypeMapping 对象一直遍历到根节点,在节点中存在元素同名属性、该属性名不为 value 且当前 annotationValueSource 属性对应索引处的元素的 distance 大于该节点的 distance 属性值时则分别将 annotationValueMappings 与 annotationValueSource 属性中对应索引处的值更新为当前节点同名属性索引与节点对象;
final class AnnotationTypeMappings {
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;
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;
}
}
}
}
isBetterConventionAnnotationValue 方法在 annotationValueMappings 属性的 index 参数索引处的值为 -1 时直接返回 true 否则在 isValueAttribute 参数为 false 且 annotationValueSource 属性的 index 参数索引处的元素的 distance 值大于 mapping 参数的 distance 属性值时返回 true;
final class AnnotationTypeMappings {
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;
}
}
5)computeSynthesizableFlag 方法
computeSynthesizableFlag 方法在 aliasMappings 属性中存在不为 -1 的元素、aliasedBy 属性不为空且 conventionMappings 属性存在不为 -1 的属性时直接返回 true;若上述条件都未能满足且不存在注解类型的属性时直接返回 false,否则在 attributes 属性中存在 synthesizable 为 true 的注解类型属性对象时直接返回 true,否则返回 false;
final class AnnotationTypeMappings {
private boolean computeSynthesizableFlag() {
for (int index : this.aliasMappings) {
if (index != -1) {
return true;
}
}
if (!this.aliasedBy.isEmpty()) {
return true;
}
for (int index : this.conventionMappings) {
if (index != -1) {
return true;
}
}
if (getAttributes().hasNestedAnnotation()) {
AttributeMethods attributeMethods = getAttributes();
for (int i = 0; i < attributeMethods.size(); i++) {
Method method = attributeMethods.get(i);
Class<?> type = method.getReturnType();
if (type.isAnnotation() || (type.isArray() && type.getComponentType().isAnnotation())) {
Class<? extends Annotation> annotationType =
(Class<? extends Annotation>) (type.isAnnotation() ? type : type.getComponentType());
AnnotationTypeMapping mapping = AnnotationTypeMappings.forAnnotationType(annotationType).get(0);
if (mapping.isSynthesizable()) {
return true;
}
}
}
}
return false;
}
}
6.2 afterAllMappingsSet 方法
afterAllMappingsSet 方法用于对对象创建后对应 claimedAliases 与 mirrorSets 属性的验证并在验证完成后清空 claimedAliases 属性中的所有元素;
final class AnnotationTypeMapping {
void afterAllMappingsSet() {
validateAllAliasesClaimed();
for (int i = 0; i < this.mirrorSets.size(); i++) {
validateMirrorSet(this.mirrorSets.get(i));
}
this.claimedAliases.clear();
}
}
6.2.1 validateAllAliasesClaimed 方法
validateAllAliasesClaimed 方法若 attribute 属性中存在使用 AliasFor 注解修饰的但未包含于 claimedAliases 属性的元素时直接抛出异常;
final class AnnotationTypeMappings {
private void validateAllAliasesClaimed() {
for (int i = 0; i < this.attributes.size(); i++) {
Method attribute = this.attributes.get(i);
AliasFor aliasFor = AnnotationsScanner.getDeclaredAnnotation(attribute, AliasFor.class);
if (aliasFor != null && !this.claimedAliases.contains(attribute)) {
Method target = resolveAliasTarget(attribute, aliasFor);
throw new AnnotationConfigurationException(String.format(
"@AliasFor declaration on %s declares an alias for %s which is not meta-present.",
AttributeMethods.describe(attribute), AttributeMethods.describe(target)));
}
}
}
}
6.2.2 validateMirrorSet 方法
validateMirrorSet 方法将 firstDefaultValue 变量值更新为 mirrorSet 参数的 attributes 属性中第一个元素对应的默认结果值,若其为空时直接抛出异常;随后对 mirrorSet 参数中所有元素进行遍历,若该元素的默认值获或第一个元素默认值为空时或其与第一个元素默认值不等时直接抛出异常;
final class AnnotationTypeMappings {
private void validateMirrorSet(MirrorSet mirrorSet) {
Method firstAttribute = mirrorSet.get(0);
Object firstDefaultValue = firstAttribute.getDefaultValue();
for (int i = 1; i <= mirrorSet.size() - 1; i++) {
Method mirrorAttribute = mirrorSet.get(i);
Object mirrorDefaultValue = mirrorAttribute.getDefaultValue();
if (firstDefaultValue == null || mirrorDefaultValue == null) {
throw new AnnotationConfigurationException(String.format(
"Misconfigured aliases: %s and %s must declare default values.",
AttributeMethods.describe(firstAttribute), AttributeMethods.describe(mirrorAttribute)));
}
if (!ObjectUtils.nullSafeEquals(firstDefaultValue, mirrorDefaultValue)) {
throw new AnnotationConfigurationException(String.format(
"Misconfigured aliases: %s and %s must declare the same default value.",
AttributeMethods.describe(firstAttribute), AttributeMethods.describe(mirrorAttribute)));
}
}
}
}
6.3 getMappedAnnotationValue 方法
getMappedAnnotationValue 方法首先从 annotationValueMappings 与 annotationValueSource 属性中 attributeIndex 参数对应位置的元素值,若 annotationValueMappings 中的对应元素为 空时直接返回 null,或 annotationValueSource 中的元素为本对象且 metaAnnotationsOnly 参数为 true 时也直接返回 null;通过上述验证后则返回 annotationValueSource 中的元素对应属性值。
final class AnnotationTypeMapping {
@Nullable
Object getMappedAnnotationValue(int attributeIndex, boolean metaAnnotationsOnly) {
int mappedIndex = this.annotationValueMappings[attributeIndex];
if (mappedIndex == -1) {
return null;
}
AnnotationTypeMapping source = this.annotationValueSource[attributeIndex];
if (source == this && metaAnnotationsOnly) {
return null;
}
return ReflectionUtils.invokeMethod(source.attributes.get(mappedIndex), source.annotation);
}
}
6.4 isEquivalentToDefaultValue 方法
isEquivalentToDefaultValue 方法首先获取 attributeIndex 参数位置处对应的属性方法对象,并使用该对象的默认值、value 及 valueExtractor 参数执行 areEquivalent 方法并返回其结果。
final class AnnotationTypeMapping {
boolean isEquivalentToDefaultValue(int attributeIndex, Object value, ValueExtractor valueExtractor) {
Method attribute = this.attributes.get(attributeIndex);
return isEquivalentToDefaultValue(attribute, value, valueExtractor);
}
private static boolean isEquivalentToDefaultValue(Method attribute, Object value,
ValueExtractor valueExtractor) {
return areEquivalent(attribute.getDefaultValue(), value, valueExtractor);
}
}
6.4.1 areEquivalent 方法
areEquivalent 方法在 value 与 extractedValue 参数相等时直接返回 true;在 value 为 Class 类型参数且 extractedValue 为字符串类型参数时,直接使用 value 与 extractedValue 参数值执行带 Class 类型参数的 areEquivalent 方法并返回、在 value 为 Class 类型数组且 extractedValue 为字符串类型数组时,则会使用 value 与 extractedValue 参数值执行带 Class 类型数组参数的 areEquivalent 方法并返回、而 value 为 Annotation 类型对象时,则使用三个入参执行带 Annotation 类型数组参数的 areEquivalent 方法并返回;否则直接返回 false。
final class AnnotationTypeMappings {
private static boolean areEquivalent(@Nullable Object value, @Nullable Object extractedValue,
ValueExtractor valueExtractor) {
if (ObjectUtils.nullSafeEquals(value, extractedValue)) {
return true;
}
if (value instanceof Class && extractedValue instanceof String) {
return areEquivalent((Class<?>) value, (String) extractedValue);
}
if (value instanceof Class[] && extractedValue instanceof String[]) {
return areEquivalent((Class[]) value, (String[]) extractedValue);
}
if (value instanceof Annotation) {
return areEquivalent((Annotation) value, extractedValue, valueExtractor);
}
return false;
}
}
1)Class 类型参数方法
带 Class 类型参数的 areEquivalent 方法直接返回 valueExtractor 参数是否为 value 类对象类名;
final class AnnotationTypeMappings {
private static boolean areEquivalent(Class<?> value, String extractedValue) {
return value.getName().equals(extractedValue);
}
}
2)Class 类型数组参数方法
带 Class 类型数组参数的 areEquivalent 方法直接返回 valueExtractor 与 value 参数是否存在类名与字符串不等的元素;
final class AnnotationTypeMappings {
private static boolean areEquivalent(Class<?>[] value, String[] extractedValue) {
if (value.length != extractedValue.length) {
return false;
}
for (int i = 0; i < value.length; i++) {
if (!areEquivalent(value[i], extractedValue[i])) {
return false;
}
}
return true;
}
}
3)Annotation 类型参数方法
带 Annotation 类型参数的 areEquivalent 方法直接则是返回 annotation 参数是否与 extractedValue 参数钟头的所有元素值相等;
final class AnnotationTypeMappings {
private static boolean areEquivalent(Annotation annotation, @Nullable Object extractedValue,
ValueExtractor valueExtractor) {
AttributeMethods attributes = AttributeMethods.forAnnotationType(annotation.annotationType());
for (int i = 0; i < attributes.size(); i++) {
Method attribute = attributes.get(i);
Object value1 = ReflectionUtils.invokeMethod(attribute, annotation);
Object value2;
if (extractedValue instanceof TypeMappedAnnotation) {
value2 = ((TypeMappedAnnotation<?>) extractedValue).getValue(attribute.getName()).orElse(null);
}
else {
value2 = valueExtractor.extract(attribute, extractedValue);
}
if (!areEquivalent(value1, value2, valueExtractor)) {
return false;
}
}
return true;
}
}
6.5 MirrorSets 内部类
6.5.1 属性及构造方法
MirrorSets 内部类拥有两个属性,这两个属性都是 MirrorSet 对象数组,其中 mirrorSets 属性保存的是, assigned 属性保存的则是;在其构造方法中分别将 assigned 与 mirrorSets 属性初始化为外部属性数组长度的 MirrorSet 对象与长度为 0 的 MirrorSet 对象;
final class AnnotationTypeMapping {
class MirrorSets {
private MirrorSet[] mirrorSets;
private final MirrorSet[] assigned;
MirrorSets() {
this.assigned = new MirrorSet[attributes.size()];
this.mirrorSets = EMPTY_MIRROR_SETS;
}
}
}
6.5.2 updateFrom 方法
updateFrom 方法首先在 aliases 参数中包含了外部 attributes 属性中的多个元素,即在本注解中存在多个互为别名的属性方法对象时,将 assigned 属性中对应索引处的元素更新为同一新建的 MirrorSet 对象;在之后若上述条件成立时,即过程中新建了 MirrorSet 对象时首先调用其 update 方法对其进行更新并将当前 assigned 属性中所有非空元素值更新到 mirrorSets 属性中。
final class AnnotationTypeMapping {
class MirrorSets {
void updateFrom(Collection<Method> 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<MirrorSet> unique = new LinkedHashSet<>(Arrays.asList(this.assigned));
unique.remove(null);
this.mirrorSets = unique.toArray(EMPTY_MIRROR_SETS);
}
}
}
}
6.5.3 mirrorSets 相关方法
size 与 get 方法分别用于获取当前保存的实际 MirrorSet 对象数量与 mirrorSets 属性中对应 index 处的 MirrorSet 对象。
final class AnnotationTypeMapping {
class MirrorSets {
int size() {
return this.mirrorSets.length;
}
MirrorSet get(int index) {
return this.mirrorSets[index];
}
}
}
6.5.4 getAssigned 方法
getAssigned 方法用于获取 assigned 属性的 attributeIndex 处的 MirrorSet 对象值;
final class AnnotationTypeMapping {
class MirrorSets {
@Nullable
MirrorSet getAssigned(int attributeIndex) {
return this.assigned[attributeIndex];
}
}
}
6.5.5 resolve 方法
resolve 方法首先将 result 初始化为大小为 attributes 长度且元素为索引值的 int 数组,随后将 mirrorSets 中所有元素对应的属性对应值更新为元素的 resolve 方法执行结果,最后返回 result 变量值;
final class AnnotationTypeMapping {
class MirrorSets {
int[] resolve(@Nullable Object source, @Nullable Object annotation, ValueExtractor 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);
int resolved = mirrorSet.resolve(source, annotation, valueExtractor);
for (int j = 0; j < mirrorSet.size; j++) {
result[mirrorSet.indexes[j]] = resolved;
}
}
return result;
}
}
}
6.6 MirrorSet 内部类
6.6.1 属性
MirrorSet 为 MirrorSets 内部类的内部类,其只拥有两个属性,size 属性存储的是 indexes 属性中实际属性属性量,indexes 属性则为外部属性数组大小的 int 数组,保存的则是外部使用该对象的索引数组;
final class AnnotationTypeMapping {
class MirrorSets {
class MirrorSet {
private int size;
private final int[] indexes = new int[attributes.size()];
int size() {
return this.size;
}
}
}
}
6.6.2 update 方法
update 方法用于外部 MirrorSets 对象更新完毕后更新本对象,其首先分别将 size 属性更新为 0 与 indexes 属性中的所有元素值全更新为 -1;随后将 MirrorSets 对象的 assigned 属性中所有为本对象的元素索引保存到 indexes 属性中,同时将 size 属性值更新为 indexes 属性中除 -1 值的元素数量,即外部 assigned 属性中等于本对象的元素数量;
final class AnnotationTypeMapping {
class MirrorSets {
class MirrorSet {
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++;
}
}
}
}
}
}
6.6.3 resolve 方法
resolve 方法用于获取 annotation 参数中本对象对应属性值;其对 indexes 属性中非 -1 值的元素进行遍历,遍历过程中首先获取元素值处对应属性方法对象,并使用 valueExtractor 参数获取 annotation 参数对应属性值,并在其为空或默认值或等于 lastValue 变量值并在 result 变量值为 -1 时将 result 变量更新为该元素值,并跳过该次循环;否则若 lastValue 不为 null 且不等于获取到的属性值时直接会抛出异常,通过该验证后直接分别将 result 与 lastValue 变量值更新为本元素值及获取到的属性值;
final class AnnotationTypeMapping {
class MirrorSets {
class MirrorSet {
<A> int resolve(@Nullable Object source, @Nullable A annotation, ValueExtractor 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.extract(attribute, annotation);
boolean isDefaultValue = (value == null ||
isEquivalentToDefaultValue(attribute, value, valueExtractor));
if (isDefaultValue || ObjectUtils.nullSafeEquals(lastValue, value)) {
if (result == -1) {
result = this.indexes[i];
}
continue;
}
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 = this.indexes[i];
lastValue = value;
}
return result;
}
}
}
}
6.6.4 get 方法
get 方法用于获取 indexes 属性的 index 参数索引处元素对应外部属性方法对象;
final class AnnotationTypeMapping {
class MirrorSets {
class MirrorSet {
Method get(int index) {
int attributeIndex = this.indexes[index];
return attributes.get(attributeIndex);
}
}
}
}
6.6.5 getAttributeIndex 方法
getAttributeIndex 方法则用于获取 indexes 属性的 index 参数索引处元素值;
final class AnnotationTypeMapping {
class MirrorSets {
class MirrorSet {
int getAttributeIndex(int index) {
return this.indexes[index];
}
}
}
}
7 AttributeMethods 类
7.1 属性及其构造方法
7.1.1 静态变量
AttributeMethods 类拥有三个静态常量,其中 NONE 保存的是空属性方法对象、cache 变量用于缓存注解的属性方法对象,其 key 值为 Annotation Class 类型对象,value 值为对应方法对象、methodComparator 则是方法对象使用的比较器对象;
final class AnnotationTypeMapping {
static final AttributeMethods NONE = new AttributeMethods(null, new Method[0]);
private static final Map<Class<? extends Annotation>, AttributeMethods> cache =
new ConcurrentReferenceHashMap<>();
private static final Comparator<Method> methodComparator = (m1, m2) -> {
if (m1 != null && m2 != null) {
return m1.getName().compareTo(m2.getName());
}
return m1 != null ? -1 : 1;
};
}
7.1.2 属性变量
AttributeMethods 类拥有保存当前方法关联注解 Class 对象的 annotationType、属性方法对象数组 attributeMethods、异常空方法值标识数组 canThrowTypeNotPresentException、 是否拥有存在默认值方法标识 hasDefaultValueMethod 及是否拥有返回值类型为注解的属性方法标识 hasNestedAnnotation 属性;
final class AnnotationTypeMapping {
@Nullable
private final Class<? extends Annotation> annotationType;
private final Method[] attributeMethods;
private final boolean[] canThrowTypeNotPresentException;
private final boolean hasDefaultValueMethod;
private final boolean hasNestedAnnotation;
@Nullable
Method get(String name) {
int index = indexOf(name);
return index != -1 ? this.attributeMethods[index] : null;
}
Method get(int index) {
return this.attributeMethods[index];
}
boolean canThrowTypeNotPresentException(int index) {
return this.canThrowTypeNotPresentException[index];
}
int indexOf(String name) {
for (int i = 0; i < this.attributeMethods.length; i++) {
if (this.attributeMethods[i].getName().equals(name)) {
return i;
}
}
return -1;
}
int indexOf(Method attribute) {
for (int i = 0; i < this.attributeMethods.length; i++) {
if (this.attributeMethods[i].equals(attribute)) {
return i;
}
}
return -1;
}
int size() {
return this.attributeMethods.length;
}
boolean hasDefaultValueMethod() {
return this.hasDefaultValueMethod;
}
boolean hasNestedAnnotation() {
return this.hasNestedAnnotation;
}
}
7.1.3 构造方法
在创建 AttributeMethods 对象的过程中首先将 annotationType 与 attributeMethods 属性初始化为对应入参值;随后将 hasDefaultValueMethod 与 hasNestedAnnotation 属性值分别初始化为 attributeMethods 数组中是否存在拥有默认返回值元素与是否存在返回值为注解对象或注解对象数组的元素,同时将 canThrowTypeNotPresentException 对应索引处的元素更新为对应索引处的方法返回值是否为 Class、Class 数组或枚举;
final class AnnotationTypeMapping {
private AttributeMethods(@Nullable Class<? extends Annotation> annotationType, Method[] attributeMethods) {
this.annotationType = annotationType;
this.attributeMethods = attributeMethods;
this.canThrowTypeNotPresentException = new boolean[attributeMethods.length];
boolean foundDefaultValueMethod = false;
boolean foundNestedAnnotation = false;
for (int i = 0; i < attributeMethods.length; i++) {
Method method = this.attributeMethods[i];
Class<?> type = method.getReturnType();
if (method.getDefaultValue() != null) {
foundDefaultValueMethod = true;
}
if (type.isAnnotation() || (type.isArray() && type.getComponentType().isAnnotation())) {
foundNestedAnnotation = true;
}
ReflectionUtils.makeAccessible(method);
this.canThrowTypeNotPresentException[i] = (type == Class.class || type == Class[].class || type.isEnum());
}
this.hasDefaultValueMethod = foundDefaultValueMethod;
this.hasNestedAnnotation = foundNestedAnnotation;
}
}
7.2 静态方法
7.2.1 forAnnotationType 方法
forAnnotationType 方法在 annotationType 参数为 null 时直接返回 null,否则尝试从 cache 常量中获取对应对象,若未获取到则使用 compute 方法创建 AttributeMethods 对象并同时将其保存到 cache 常量中并返回;
final class AnnotationTypeMapping {
static AttributeMethods forAnnotationType(@Nullable Class<? extends Annotation> annotationType) {
if (annotationType == null) {
return NONE;
}
return cache.computeIfAbsent(annotationType, AttributeMethods::compute);
}
}
compute 方法首先将 annotationType 参数中所有无参且返回值不为 void 的方法转化为 Method 数组并使用 methodComparator 常量对其进行排序;若处理后 Method 数组没有任何元素则直接返回 NONE 常量,否则使用该数组与 annotationType 参数创建 AttributeMethods 对象并返回;
final class AnnotationTypeMapping {
private static AttributeMethods compute(Class<? extends Annotation> annotationType) {
Method[] methods = annotationType.getDeclaredMethods();
int size = methods.length;
for (int i = 0; i < methods.length; i++) {
if (!isAttributeMethod(methods[i])) {
methods[i] = null;
size--;
}
}
if (size == 0) {
return NONE;
}
Arrays.sort(methods, methodComparator);
Method[] attributeMethods = Arrays.copyOf(methods, size);
return new AttributeMethods(annotationType, attributeMethods);
}
private static boolean isAttributeMethod(Method method) {
return (method.getParameterCount() == 0 && method.getReturnType() != void.class);
}
}
7.2.2 describe 方法
describe 方法在 attribute 参数为 null 时直接返回"(none)",否则使用 attribute 参数所属注解对象类作为 annotationType 参数及其名称作为 attributeName 参数执行两个参数的 describe 方法;随后若 attributeName 参数为 null 也是直接返回 "(none)",否则返回 "attribute '" + attributeName + "'" + " in annotation [" + annotationType.getName() + "]" 字符串值。
final class AnnotationTypeMapping {
static String describe(@Nullable Method attribute) {
if (attribute == null) {
return "(none)";
}
return describe(attribute.getDeclaringClass(), attribute.getName());
}
static String describe(@Nullable Class<?> annotationType, @Nullable String attributeName) {
if (attributeName == null) {
return "(none)";
}
String in = (annotationType != null ? " in annotation [" + annotationType.getName() + "]" : "");
return "attribute '" + attributeName + "'" + in;
}
}
四 MetadataReader 对象工厂
MetadataReader 对象工厂的顶层接口工厂为 MetadataReaderFactory 接口,其只有一个 SimpleMetadataReaderFactory 直接实现类,SimpleMetadataReaderFactory 类也只有一个子类—— CachingMetadataReaderFactory;
1 MetadataReaderFactory 接口
MetadataReaderFactory 接口拥有两个不同的获取 MetadataReader 的方法,一个直接使用 className 类名构建 MetadataReader 对象,另一个则是使用 Resource 资源对象构建对象;
public interface MetadataReaderFactory {
MetadataReader getMetadataReader(String className) throws IOException;
MetadataReader getMetadataReader(Resource resource) throws IOException;
}
2 SimpleMetadataReaderFactory 类
2.1 属性变量
SimpleMetadataReaderFactory 类只有一个保存使用的类加载器的 resourceLoader 属性;
public class SimpleMetadataReaderFactory implements MetadataReaderFactory {
private final ResourceLoader resourceLoader;
public final ResourceLoader getResourceLoader() {
return this.resourceLoader;
}
}
2.2 构造方法
SimpleMetadataReaderFactory 类拥有三个不同的构造方法,其分别为无参构造方法,拥有 ResourceLoader 资源加载器参数构造方法及拥有 ClassLoader 类加载器参数的构造方法;在对象创建过程中,拥有 ResourceLoader 参数且不为 null 时,将 resourceLoader 属性初始化为 ResourceLoader 参数值,拥有 ClassLoader 参数且不为 null 时,使用该参数将 resourceLoader 属性初始化为 DefaultResourceLoader 对象,否则将 resourceLoader 属性初始化为空 DefaultResourceLoader 对象;
public class SimpleMetadataReaderFactory implements MetadataReaderFactory {
public SimpleMetadataReaderFactory() {
this.resourceLoader = new DefaultResourceLoader();
}
public SimpleMetadataReaderFactory(@Nullable ResourceLoader resourceLoader) {
this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
}
public SimpleMetadataReaderFactory(@Nullable ClassLoader classLoader) {
this.resourceLoader =
(classLoader != null ? new DefaultResourceLoader(classLoader) : new DefaultResourceLoader());
}
}
2.3 getMetadataReader 方法
className 类名参数的 getMetadataReader 方法直接使用 resourceLoader 获取 className 参数对应类文件资源,并使用获取到资源调用另一个 getMetadataReader 方法并返回结果;若上述过程中抛出了 FileNotFoundException 异常时,在 className 参数中不包含 . 字符时直接抛出该异常,否则使用 $ 替换最后一个 . 字符,即尝试将该类当作内部类,随后使用替换后的字符串尝试从 resourceLoader 属性加载类资源并在该资源存在时使用该资源调用第二个 getMetadataReader 方法并返回其结果,否则也会抛出异常;
public class SimpleMetadataReaderFactory implements MetadataReaderFactory {
@Override
public MetadataReader getMetadataReader(String className) throws IOException {
try {
String resourcePath = ResourceLoader.CLASSPATH_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(className) + ClassUtils.CLASS_FILE_SUFFIX;
Resource resource = this.resourceLoader.getResource(resourcePath);
return getMetadataReader(resource);
}
catch (FileNotFoundException ex) {
int lastDotIndex = className.lastIndexOf('.');
if (lastDotIndex != -1) {
String innerClassName =
className.substring(0, lastDotIndex) + '$' + className.substring(lastDotIndex + 1);
String innerClassResourcePath = ResourceLoader.CLASSPATH_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(innerClassName) + ClassUtils.CLASS_FILE_SUFFIX;
Resource innerClassResource = this.resourceLoader.getResource(innerClassResourcePath);
if (innerClassResource.exists()) {
return getMetadataReader(innerClassResource);
}
}
throw ex;
}
}
}
className 类名参数的 getMetadataReader 方法直接使用 resourceLoader 获取 className 参数对应类文件资源,并使用获取到资源调用另一个 getMetadataReader 方法并返回结果;若上述过程中抛出了 FileNotFoundException 异常时,在 className 参数中不包含 . 字符时直接抛出该异常,否则使用 $ 替换最后一个 . 字符,即尝试将该类当作内部类,随后使用替换后的字符串尝试从 resourceLoader 属性加载类资源并在该资源存在时使用该资源调用第二个 getMetadataReader 方法并返回其结果,否则也会抛出异常;
public class SimpleMetadataReaderFactory implements MetadataReaderFactory {
@Override
public MetadataReader getMetadataReader(Resource resource) throws IOException {
return new SimpleMetadataReader(resource, this.resourceLoader.getClassLoader());
}
}
3 CachingMetadataReaderFactory 类
3.1 属性及其构造方法
3.1.1 静态变量
CachingMetadataReaderFactory 类只有一个用于存储默认缓存容量的 DEFAULT_CACHE_LIMIT 常量,其值为 256;
public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
public static final int DEFAULT_CACHE_LIMIT = 256;
}
3.1.2 属性变量
CachingMetadataReaderFactory 类只扩展了一个属性变量,即用于缓存 MetadataReader 对象的 metadataReaderCache 属性,其 key 为元数据读取对象的关联资源对象,value 值则是缓存的对应 MetadataReader 对象;
public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
@Nullable
private Map<Resource, MetadataReader> metadataReaderCache;
}
3.1.3 构造方法
CachingMetadataReaderFactory 类和其父类一样,也拥有三个不同的构造方法,其在调用父类对应构造方法之后,都会对 metadataReaderCache 缓存属性进行初始化,其中只有在入参类型为 ResourceLoader 且在该对象为 DefaultResourceLoader 对象时直接将 metadataReaderCache 属性初始化为其 getResourceCache 方法执行结果,而在其他情况下直接调用 setCacheLimit 方法将缓存容量限制为 DEFAULT_CACHE_LIMIT 常量值;
public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
public CachingMetadataReaderFactory() {
super();
setCacheLimit(DEFAULT_CACHE_LIMIT);
}
public CachingMetadataReaderFactory(@Nullable ClassLoader classLoader) {
super(classLoader);
setCacheLimit(DEFAULT_CACHE_LIMIT);
}
public CachingMetadataReaderFactory(@Nullable ResourceLoader resourceLoader) {
super(resourceLoader);
if (resourceLoader instanceof DefaultResourceLoader) {
this.metadataReaderCache =
((DefaultResourceLoader) resourceLoader).getResourceCache(MetadataReader.class);
}
else {
setCacheLimit(DEFAULT_CACHE_LIMIT);
}
}
}
3.2 setCacheLimit 方法
setCacheLimit 方法在 cacheLimit 参数不大于 0 时将 metadataReaderCache 属性更新为 null,而在 metadataReaderCache 属性为 LocalResourceCache 对象时直接调用其 setCacheLimit 方法将其缓存容量限制为 cacheLimit 参数大小,否则使用 cacheLimit 参数创建 LocalResourceCache 对象并将其保存到 metadataReaderCache 属性中;
public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
public void setCacheLimit(int cacheLimit) {
if (cacheLimit <= 0) {
this.metadataReaderCache = null;
}
else if (this.metadataReaderCache instanceof LocalResourceCache) {
((LocalResourceCache) this.metadataReaderCache).setCacheLimit(cacheLimit);
}
else {
this.metadataReaderCache = new LocalResourceCache(cacheLimit);
}
}
}
3.3 getCacheLimit 方法
getCacheLimit 方法在 metadataReaderCache 属性为 LocalResourceCache 对象时直接调用其 getCacheLimit 方法获取其容量限制并返回,否则根据 metadataReaderCache 属性是否为空,而返回 0 或最大整型数;
public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
public int getCacheLimit() {
if (this.metadataReaderCache instanceof LocalResourceCache) {
return ((LocalResourceCache) this.metadataReaderCache).getCacheLimit();
}
else {
return (this.metadataReaderCache != null ? Integer.MAX_VALUE : 0);
}
}
}
3.4 getMetadataReader 方法
getMetadataReader 方法在 metadataReaderCache 属性为 ConcurrentMap 对象,即其操作是线程安全的时,直接获取 resource 参数对应的 MetadataReader 对象并在其为 null 时调用父类的 getMetadataReader 方法创建 MetadataReader 对象并保存到 metadataReaderCache 属性中同时返回;在 metadataReaderCache 属性不为 null 是,则使用 synchronized 关键字执行上述逻辑并返回;最后在 metadataReaderCache 属性为 null 时,直接调用父类的 getMetadataReader 方法创建 MetadataReader 对象并返回。
public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
@Override
public MetadataReader getMetadataReader(Resource resource) throws IOException {
if (this.metadataReaderCache instanceof ConcurrentMap) {
MetadataReader metadataReader = this.metadataReaderCache.get(resource);
if (metadataReader == null) {
metadataReader = super.getMetadataReader(resource);
this.metadataReaderCache.put(resource, metadataReader);
}
return metadataReader;
}
else if (this.metadataReaderCache != null) {
synchronized (this.metadataReaderCache) {
MetadataReader metadataReader = this.metadataReaderCache.get(resource);
if (metadataReader == null) {
metadataReader = super.getMetadataReader(resource);
this.metadataReaderCache.put(resource, metadataReader);
}
return metadataReader;
}
}
else {
return super.getMetadataReader(resource);
}
}
}
3.5 clearCache 方法
clearCache 方法在 metadataReaderCache 属性为 LocalResourceCache 对象时,使用 synchronized 关键字锁住 metadataReaderCache 属性并调用其 clear 方法情况缓存;否则在该属性不为空时直接调用 setCacheLimit 方法滴重置该属性。
public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
public void clearCache() {
if (this.metadataReaderCache instanceof LocalResourceCache) {
synchronized (this.metadataReaderCache) {
this.metadataReaderCache.clear();
}
}
else if (this.metadataReaderCache != null) {
setCacheLimit(DEFAULT_CACHE_LIMIT);
}
}
}
3.5 LocalResourceCache 内部类
LocalResourceCache 内部类为 LinkedHashMap 的子类,其使用 cacheLimit 属性扩展了缓存容量限制;同时重写了 removeEldestEntry 方法使其在新增节点后元素量大于 cacheLimit 属性时移除最老的节点。
public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
private static class LocalResourceCache extends LinkedHashMap<Resource, MetadataReader> {
private volatile int cacheLimit;
public LocalResourceCache(int cacheLimit) {
super(cacheLimit, 0.75f, true);
this.cacheLimit = cacheLimit;
}
public void setCacheLimit(int cacheLimit) {
this.cacheLimit = cacheLimit;
}
public int getCacheLimit() {
return this.cacheLimit;
}
@Override
protected boolean removeEldestEntry(Map.Entry<Resource, MetadataReader> eldest) {
return size() > this.cacheLimit;
}
}
}