Apply "instanceof pattern matching" in core annotation support

This commit is contained in:
Sam Brannen 2022-03-18 17:24:01 +01:00
parent 2fb1dd177b
commit 5c540e5390
10 changed files with 72 additions and 79 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -794,7 +794,7 @@ public abstract class AnnotatedElementUtils {
/** /**
* Adapted {@link AnnotatedElement} that hold specific annotations. * Adapted {@link AnnotatedElement} that holds specific annotations.
*/ */
private static class AnnotatedElementForAnnotations implements AnnotatedElement { private static class AnnotatedElementForAnnotations implements AnnotatedElement {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -369,10 +369,10 @@ public class AnnotationAttributes extends LinkedHashMap<String, Object> {
} }
private void assertNotException(String attributeName, Object attributeValue) { private void assertNotException(String attributeName, Object attributeValue) {
if (attributeValue instanceof Throwable) { if (attributeValue instanceof Throwable throwable) {
throw new IllegalArgumentException(String.format( throw new IllegalArgumentException(String.format(
"Attribute '%s' for annotation [%s] was not resolvable due to exception [%s]", "Attribute '%s' for annotation [%s] was not resolvable due to exception [%s]",
attributeName, this.displayName, attributeValue), (Throwable) attributeValue); attributeName, this.displayName, attributeValue), throwable);
} }
} }
@ -406,8 +406,8 @@ public class AnnotationAttributes extends LinkedHashMap<String, Object> {
if (value == this) { if (value == this) {
return "(this Map)"; return "(this Map)";
} }
if (value instanceof Object[]) { if (value instanceof Object[] objects) {
return "[" + StringUtils.arrayToDelimitedString((Object[]) value, ", ") + "]"; return "[" + StringUtils.arrayToDelimitedString(objects, ", ") + "]";
} }
return String.valueOf(value); return String.valueOf(value);
} }
@ -426,8 +426,8 @@ public class AnnotationAttributes extends LinkedHashMap<String, Object> {
if (map == null) { if (map == null) {
return null; return null;
} }
if (map instanceof AnnotationAttributes) { if (map instanceof AnnotationAttributes annotationAttributes) {
return (AnnotationAttributes) map; return annotationAttributes;
} }
return new AnnotationAttributes(map); return new AnnotationAttributes(map);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -73,8 +73,8 @@ public class AnnotationAwareOrderComparator extends OrderComparator {
AnnotatedElement element = (obj instanceof AnnotatedElement ? (AnnotatedElement) obj : obj.getClass()); AnnotatedElement element = (obj instanceof AnnotatedElement ? (AnnotatedElement) obj : obj.getClass());
MergedAnnotations annotations = MergedAnnotations.from(element, SearchStrategy.TYPE_HIERARCHY); MergedAnnotations annotations = MergedAnnotations.from(element, SearchStrategy.TYPE_HIERARCHY);
Integer order = OrderUtils.getOrderFromAnnotations(element, annotations); Integer order = OrderUtils.getOrderFromAnnotations(element, annotations);
if (order == null && obj instanceof DecoratingProxy) { if (order == null && obj instanceof DecoratingProxy decoratingProxy) {
return findOrderFromAnnotation(((DecoratingProxy) obj).getDecoratedClass()); return findOrderFromAnnotation(decoratingProxy.getDecoratedClass());
} }
return order; return order;
} }
@ -88,12 +88,12 @@ public class AnnotationAwareOrderComparator extends OrderComparator {
@Override @Override
@Nullable @Nullable
public Integer getPriority(Object obj) { public Integer getPriority(Object obj) {
if (obj instanceof Class) { if (obj instanceof Class<?> clazz) {
return OrderUtils.getPriority((Class<?>) obj); return OrderUtils.getPriority(clazz);
} }
Integer priority = OrderUtils.getPriority(obj.getClass()); Integer priority = OrderUtils.getPriority(obj.getClass());
if (priority == null && obj instanceof DecoratingProxy) { if (priority == null && obj instanceof DecoratingProxy decoratingProxy) {
return getPriority(((DecoratingProxy) obj).getDecoratedClass()); return getPriority(decoratingProxy.getDecoratedClass());
} }
return priority; return priority;
} }
@ -134,11 +134,11 @@ public class AnnotationAwareOrderComparator extends OrderComparator {
* @see java.util.Arrays#sort(Object[], java.util.Comparator) * @see java.util.Arrays#sort(Object[], java.util.Comparator)
*/ */
public static void sortIfNecessary(Object value) { public static void sortIfNecessary(Object value) {
if (value instanceof Object[]) { if (value instanceof Object[] objects) {
sort((Object[]) value); sort(objects);
} }
else if (value instanceof List) { else if (value instanceof List<?> list) {
sort((List<?>) value); sort(list);
} }
} }

View File

@ -561,14 +561,14 @@ final class AnnotationTypeMapping {
if (ObjectUtils.nullSafeEquals(value, extractedValue)) { if (ObjectUtils.nullSafeEquals(value, extractedValue)) {
return true; return true;
} }
if (value instanceof Class && extractedValue instanceof String) { if (value instanceof Class<?> clazz && extractedValue instanceof String string) {
return areEquivalent((Class<?>) value, (String) extractedValue); return areEquivalent(clazz, string);
} }
if (value instanceof Class[] && extractedValue instanceof String[]) { if (value instanceof Class<?>[] classes && extractedValue instanceof String[] strings) {
return areEquivalent((Class[]) value, (String[]) extractedValue); return areEquivalent(classes, strings);
} }
if (value instanceof Annotation) { if (value instanceof Annotation annotation) {
return areEquivalent((Annotation) value, extractedValue, valueExtractor); return areEquivalent(annotation, extractedValue, valueExtractor);
} }
return false; return false;
} }
@ -597,8 +597,8 @@ final class AnnotationTypeMapping {
Method attribute = attributes.get(i); Method attribute = attributes.get(i);
Object value1 = ReflectionUtils.invokeMethod(attribute, annotation); Object value1 = ReflectionUtils.invokeMethod(attribute, annotation);
Object value2; Object value2;
if (extractedValue instanceof TypeMappedAnnotation) { if (extractedValue instanceof TypeMappedAnnotation<?> typeMappedAnnotation) {
value2 = ((TypeMappedAnnotation<?>) extractedValue).getValue(attribute.getName()).orElse(null); value2 = typeMappedAnnotation.getValue(attribute.getName()).orElse(null);
} }
else { else {
value2 = valueExtractor.extract(attribute, extractedValue); value2 = valueExtractor.extract(attribute, extractedValue);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -976,8 +976,8 @@ public abstract class AnnotationUtils {
for (Map.Entry<String, Object> attributeEntry : attributes.entrySet()) { for (Map.Entry<String, Object> attributeEntry : attributes.entrySet()) {
String attributeName = attributeEntry.getKey(); String attributeName = attributeEntry.getKey();
Object value = attributeEntry.getValue(); Object value = attributeEntry.getValue();
if (value instanceof DefaultValueHolder) { if (value instanceof DefaultValueHolder defaultValueHolder) {
value = ((DefaultValueHolder) value).defaultValue; value = defaultValueHolder.defaultValue;
attributes.put(attributeName, attributes.put(attributeName,
adaptValue(annotatedElement, value, classValuesAsString)); adaptValue(annotatedElement, value, classValuesAsString));
} }
@ -986,7 +986,7 @@ public abstract class AnnotationUtils {
private static Object getAttributeValueForMirrorResolution(Method attribute, Object attributes) { private static Object getAttributeValueForMirrorResolution(Method attribute, Object attributes) {
Object result = ((AnnotationAttributes) attributes).get(attribute.getName()); Object result = ((AnnotationAttributes) attributes).get(attribute.getName());
return (result instanceof DefaultValueHolder ? ((DefaultValueHolder) result).defaultValue : result); return (result instanceof DefaultValueHolder defaultValueHolder ? defaultValueHolder.defaultValue : result);
} }
@Nullable @Nullable
@ -994,11 +994,10 @@ public abstract class AnnotationUtils {
@Nullable Object annotatedElement, @Nullable Object value, boolean classValuesAsString) { @Nullable Object annotatedElement, @Nullable Object value, boolean classValuesAsString) {
if (classValuesAsString) { if (classValuesAsString) {
if (value instanceof Class) { if (value instanceof Class<?> clazz) {
return ((Class<?>) value).getName(); return clazz.getName();
} }
if (value instanceof Class[]) { if (value instanceof Class<?>[] classes) {
Class<?>[] classes = (Class<?>[]) value;
String[] names = new String[classes.length]; String[] names = new String[classes.length];
for (int i = 0; i < classes.length; i++) { for (int i = 0; i < classes.length; i++) {
names[i] = classes[i].getName(); names[i] = classes[i].getName();
@ -1099,7 +1098,7 @@ public abstract class AnnotationUtils {
rethrowAnnotationConfigurationException(ex); rethrowAnnotationConfigurationException(ex);
IntrospectionFailureLogger logger = IntrospectionFailureLogger.INFO; IntrospectionFailureLogger logger = IntrospectionFailureLogger.INFO;
boolean meta = false; boolean meta = false;
if (element instanceof Class && Annotation.class.isAssignableFrom((Class<?>) element)) { if (element instanceof Class<?> clazz && Annotation.class.isAssignableFrom(clazz)) {
// Meta-annotation or (default) value lookup on an annotation type // Meta-annotation or (default) value lookup on an annotation type
logger = IntrospectionFailureLogger.DEBUG; logger = IntrospectionFailureLogger.DEBUG;
meta = true; meta = true;

View File

@ -82,11 +82,11 @@ abstract class AnnotationsScanner {
private static <C, R> R process(C context, AnnotatedElement source, private static <C, R> R process(C context, AnnotatedElement source,
SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) { SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
if (source instanceof Class) { if (source instanceof Class<?> clazz) {
return processClass(context, (Class<?>) source, searchStrategy, processor); return processClass(context, clazz, searchStrategy, processor);
} }
if (source instanceof Method) { if (source instanceof Method method) {
return processMethod(context, (Method) source, searchStrategy, processor); return processMethod(context, method, searchStrategy, processor);
} }
return processElement(context, source, processor); return processElement(context, source, processor);
} }
@ -477,7 +477,7 @@ abstract class AnnotationsScanner {
return true; return true;
} }
if (searchStrategy == SearchStrategy.DIRECT || isWithoutHierarchy(source, searchStrategy)) { if (searchStrategy == SearchStrategy.DIRECT || isWithoutHierarchy(source, searchStrategy)) {
if (source instanceof Method && ((Method) source).isBridge()) { if (source instanceof Method method && method.isBridge()) {
return false; return false;
} }
return getDeclaredAnnotations(source, false).length == 0; return getDeclaredAnnotations(source, false).length == 0;
@ -486,11 +486,11 @@ abstract class AnnotationsScanner {
} }
static boolean hasPlainJavaAnnotationsOnly(@Nullable Object annotatedElement) { static boolean hasPlainJavaAnnotationsOnly(@Nullable Object annotatedElement) {
if (annotatedElement instanceof Class) { if (annotatedElement instanceof Class<?> clazz) {
return hasPlainJavaAnnotationsOnly((Class<?>) annotatedElement); return hasPlainJavaAnnotationsOnly(clazz);
} }
else if (annotatedElement instanceof Member) { else if (annotatedElement instanceof Member member) {
return hasPlainJavaAnnotationsOnly(((Member) annotatedElement).getDeclaringClass()); return hasPlainJavaAnnotationsOnly(member.getDeclaringClass());
} }
else { else {
return false; return false;
@ -506,8 +506,7 @@ abstract class AnnotationsScanner {
if (source == Object.class) { if (source == Object.class) {
return true; return true;
} }
if (source instanceof Class) { if (source instanceof Class<?> sourceClass) {
Class<?> sourceClass = (Class<?>) source;
boolean noSuperTypes = (sourceClass.getSuperclass() == Object.class && boolean noSuperTypes = (sourceClass.getSuperclass() == Object.class &&
sourceClass.getInterfaces().length == 0); sourceClass.getInterfaces().length == 0);
return (searchStrategy == SearchStrategy.TYPE_HIERARCHY_AND_ENCLOSING_CLASSES ? noSuperTypes && return (searchStrategy == SearchStrategy.TYPE_HIERARCHY_AND_ENCLOSING_CLASSES ? noSuperTypes &&

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -74,7 +74,7 @@ public abstract class MergedAnnotationPredicates {
*/ */
public static <A extends Annotation> Predicate<MergedAnnotation<? extends A>> typeIn(Collection<?> types) { public static <A extends Annotation> Predicate<MergedAnnotation<? extends A>> typeIn(Collection<?> types) {
return annotation -> types.stream() return annotation -> types.stream()
.map(type -> type instanceof Class ? ((Class<?>) type).getName() : type.toString()) .map(type -> type instanceof Class<?> clazz ? clazz.getName() : type.toString())
.anyMatch(typeName -> typeName.equals(annotation.getType().getName())); .anyMatch(typeName -> typeName.equals(annotation.getType().getName()));
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -111,7 +111,7 @@ public abstract class OrderUtils {
} }
Object cached = orderCache.get(element); Object cached = orderCache.get(element);
if (cached != null) { if (cached != null) {
return (cached instanceof Integer ? (Integer) cached : null); return (cached instanceof Integer integer ? integer : null);
} }
Integer result = findOrder(annotations); Integer result = findOrder(annotations);
orderCache.put(element, result != null ? result : NOT_ANNOTATED); orderCache.put(element, result != null ? result : NOT_ANNOTATED);

View File

@ -120,11 +120,11 @@ public class SynthesizingMethodParameter extends MethodParameter {
* @since 5.0 * @since 5.0
*/ */
public static SynthesizingMethodParameter forExecutable(Executable executable, int parameterIndex) { public static SynthesizingMethodParameter forExecutable(Executable executable, int parameterIndex) {
if (executable instanceof Method) { if (executable instanceof Method method) {
return new SynthesizingMethodParameter((Method) executable, parameterIndex); return new SynthesizingMethodParameter(method, parameterIndex);
} }
else if (executable instanceof Constructor) { else if (executable instanceof Constructor<?> constructor) {
return new SynthesizingMethodParameter((Constructor<?>) executable, parameterIndex); return new SynthesizingMethodParameter(constructor, parameterIndex);
} }
else { else {
throw new IllegalArgumentException("Not a Method/Constructor: " + executable); throw new IllegalArgumentException("Not a Method/Constructor: " + executable);

View File

@ -297,13 +297,11 @@ final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnn
private <T extends Map<String, Object>> Object adaptValueForMapOptions(Method attribute, Object value, private <T extends Map<String, Object>> Object adaptValueForMapOptions(Method attribute, Object value,
Class<?> mapType, Function<MergedAnnotation<?>, T> factory, Adapt[] adaptations) { Class<?> mapType, Function<MergedAnnotation<?>, T> factory, Adapt[] adaptations) {
if (value instanceof MergedAnnotation) { if (value instanceof MergedAnnotation<?> annotation) {
MergedAnnotation<?> annotation = (MergedAnnotation<?>) value;
return (Adapt.ANNOTATION_TO_MAP.isIn(adaptations) ? return (Adapt.ANNOTATION_TO_MAP.isIn(adaptations) ?
annotation.asMap(factory, adaptations) : annotation.synthesize()); annotation.asMap(factory, adaptations) : annotation.synthesize());
} }
if (value instanceof MergedAnnotation[]) { if (value instanceof MergedAnnotation<?>[] annotations) {
MergedAnnotation<?>[] annotations = (MergedAnnotation<?>[]) value;
if (Adapt.ANNOTATION_TO_MAP.isIn(adaptations)) { if (Adapt.ANNOTATION_TO_MAP.isIn(adaptations)) {
Object result = Array.newInstance(mapType, annotations.length); Object result = Array.newInstance(mapType, annotations.length);
for (int i = 0; i < annotations.length; i++) { for (int i = 0; i < annotations.length; i++) {
@ -420,14 +418,13 @@ final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnn
} }
value = adaptForAttribute(attribute, value); value = adaptForAttribute(attribute, value);
type = getAdaptType(attribute, type); type = getAdaptType(attribute, type);
if (value instanceof Class && type == String.class) { if (value instanceof Class<?> clazz && type == String.class) {
value = ((Class<?>) value).getName(); value = clazz.getName();
} }
else if (value instanceof String && type == Class.class) { else if (value instanceof String str && type == Class.class) {
value = ClassUtils.resolveClassName((String) value, getClassLoader()); value = ClassUtils.resolveClassName(str, getClassLoader());
} }
else if (value instanceof Class[] && type == String[].class) { else if (value instanceof Class<?>[] classes && type == String[].class) {
Class<?>[] classes = (Class<?>[]) value;
String[] names = new String[classes.length]; String[] names = new String[classes.length];
for (int i = 0; i < classes.length; i++) { for (int i = 0; i < classes.length; i++) {
names[i] = classes[i].getName(); names[i] = classes[i].getName();
@ -441,12 +438,11 @@ final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnn
} }
value = classes; value = classes;
} }
else if (value instanceof MergedAnnotation && type.isAnnotation()) { else if (value instanceof MergedAnnotation<?> annotation && type.isAnnotation()) {
MergedAnnotation<?> annotation = (MergedAnnotation<?>) value;
value = annotation.synthesize(); value = annotation.synthesize();
} }
else if (value instanceof MergedAnnotation[] && type.isArray() && type.getComponentType().isAnnotation()) { else if (value instanceof MergedAnnotation<?>[] annotations &&
MergedAnnotation<?>[] annotations = (MergedAnnotation<?>[]) value; type.isArray() && type.getComponentType().isAnnotation()) {
Object array = Array.newInstance(type.getComponentType(), annotations.length); Object array = Array.newInstance(type.getComponentType(), annotations.length);
for (int i = 0; i < annotations.length; i++) { for (int i = 0; i < annotations.length; i++) {
Array.set(array, i, annotations[i].synthesize()); Array.set(array, i, annotations[i].synthesize());
@ -498,7 +494,7 @@ final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnn
} }
private boolean isEmptyObjectArray(Object value) { private boolean isEmptyObjectArray(Object value) {
return (value instanceof Object[] && ((Object[]) value).length == 0); return (value instanceof Object[] objects && objects.length == 0);
} }
private Object emptyArray(Class<?> componentType) { private Object emptyArray(Class<?> componentType) {
@ -510,8 +506,8 @@ final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnn
} }
private MergedAnnotation<?> adaptToMergedAnnotation(Object value, Class<? extends Annotation> annotationType) { private MergedAnnotation<?> adaptToMergedAnnotation(Object value, Class<? extends Annotation> annotationType) {
if (value instanceof MergedAnnotation) { if (value instanceof MergedAnnotation<?> mergedAnnotation) {
return (MergedAnnotation<?>) value; return mergedAnnotation;
} }
AnnotationTypeMapping mapping = AnnotationTypeMappings.forAnnotationType(annotationType).get(0); AnnotationTypeMapping mapping = AnnotationTypeMappings.forAnnotationType(annotationType).get(0);
return new TypeMappedAnnotation<>( return new TypeMappedAnnotation<>(
@ -566,11 +562,11 @@ final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnn
return this.classLoader; return this.classLoader;
} }
if (this.source != null) { if (this.source != null) {
if (this.source instanceof Class) { if (this.source instanceof Class<?> clazz) {
return ((Class<?>) this.source).getClassLoader(); return clazz.getClassLoader();
} }
if (this.source instanceof Member) { if (this.source instanceof Member member) {
((Member) this.source).getDeclaringClass().getClassLoader(); member.getDeclaringClass().getClassLoader();
} }
} }
return null; return null;
@ -597,8 +593,7 @@ final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnn
static <A extends Annotation> TypeMappedAnnotation<A> createIfPossible( static <A extends Annotation> TypeMappedAnnotation<A> createIfPossible(
AnnotationTypeMapping mapping, MergedAnnotation<?> annotation, IntrospectionFailureLogger logger) { AnnotationTypeMapping mapping, MergedAnnotation<?> annotation, IntrospectionFailureLogger logger) {
if (annotation instanceof TypeMappedAnnotation) { if (annotation instanceof TypeMappedAnnotation<?> typeMappedAnnotation) {
TypeMappedAnnotation<?> typeMappedAnnotation = (TypeMappedAnnotation<?>) annotation;
return createIfPossible(mapping, typeMappedAnnotation.source, return createIfPossible(mapping, typeMappedAnnotation.source,
typeMappedAnnotation.rootAttributes, typeMappedAnnotation.rootAttributes,
typeMappedAnnotation.valueExtractor, typeMappedAnnotation.valueExtractor,