Apply "instanceof pattern matching" in spring-core

Closes gh-28188
This commit is contained in:
diguage
2022-03-17 00:13:13 +08:00
committed by Sam Brannen
parent 720261db26
commit bbaf7578b2
33 changed files with 245 additions and 251 deletions

View File

@@ -154,9 +154,9 @@ public final class GenericTypeResolver {
*/
public static Type resolveType(Type genericType, @Nullable Class<?> contextClass) {
if (contextClass != null) {
if (genericType instanceof TypeVariable) {
if (genericType instanceof TypeVariable<?> typeVariable) {
ResolvableType resolvedTypeVariable = resolveVariable(
(TypeVariable<?>) genericType, ResolvableType.forClass(contextClass));
typeVariable, ResolvableType.forClass(contextClass));
if (resolvedTypeVariable != ResolvableType.NONE) {
Class<?> resolved = resolvedTypeVariable.resolve();
if (resolved != null) {
@@ -164,10 +164,9 @@ public final class GenericTypeResolver {
}
}
}
else if (genericType instanceof ParameterizedType) {
else if (genericType instanceof ParameterizedType parameterizedType) {
ResolvableType resolvedType = ResolvableType.forType(genericType);
if (resolvedType.hasUnresolvableGenerics()) {
ParameterizedType parameterizedType = (ParameterizedType) genericType;
Class<?>[] generics = new Class<?>[parameterizedType.getActualTypeArguments().length];
Type[] typeArguments = parameterizedType.getActualTypeArguments();
ResolvableType contextType = ResolvableType.forClass(contextClass);

View File

@@ -552,20 +552,20 @@ public class MethodParameter {
if (this.nestingLevel > 1) {
Type type = getGenericParameterType();
for (int i = 2; i <= this.nestingLevel; i++) {
if (type instanceof ParameterizedType) {
Type[] args = ((ParameterizedType) type).getActualTypeArguments();
if (type instanceof ParameterizedType parameterizedType) {
Type[] args = parameterizedType.getActualTypeArguments();
Integer index = getTypeIndexForLevel(i);
type = args[index != null ? index : args.length - 1];
}
// TODO: Object.class if unresolvable
}
if (type instanceof Class) {
return (Class<?>) type;
if (type instanceof Class<?> clazz) {
return clazz;
}
else if (type instanceof ParameterizedType) {
Type arg = ((ParameterizedType) type).getRawType();
if (arg instanceof Class) {
return (Class<?>) arg;
else if (type instanceof ParameterizedType parameterizedType) {
Type arg = parameterizedType.getRawType();
if (arg instanceof Class<?> clazz) {
return clazz;
}
}
return Object.class;
@@ -585,8 +585,8 @@ public class MethodParameter {
if (this.nestingLevel > 1) {
Type type = getGenericParameterType();
for (int i = 2; i <= this.nestingLevel; i++) {
if (type instanceof ParameterizedType) {
Type[] args = ((ParameterizedType) type).getActualTypeArguments();
if (type instanceof ParameterizedType parameterizedType) {
Type[] args = parameterizedType.getActualTypeArguments();
Integer index = getTypeIndexForLevel(i);
type = args[index != null ? index : args.length - 1];
}
@@ -708,11 +708,11 @@ public class MethodParameter {
ParameterNameDiscoverer discoverer = this.parameterNameDiscoverer;
if (discoverer != null) {
String[] parameterNames = null;
if (this.executable instanceof Method) {
parameterNames = discoverer.getParameterNames((Method) this.executable);
if (this.executable instanceof Method method) {
parameterNames = discoverer.getParameterNames(method);
}
else if (this.executable instanceof Constructor) {
parameterNames = discoverer.getParameterNames((Constructor<?>) this.executable);
else if (this.executable instanceof Constructor<?> constructor) {
parameterNames = discoverer.getParameterNames(constructor);
}
if (parameterNames != null) {
this.parameterName = parameterNames[this.parameterIndex];
@@ -791,11 +791,11 @@ public class MethodParameter {
*/
@Deprecated
public static MethodParameter forMethodOrConstructor(Object methodOrConstructor, int parameterIndex) {
if (!(methodOrConstructor instanceof Executable)) {
if (!(methodOrConstructor instanceof Executable executable)) {
throw new IllegalArgumentException(
"Given object [" + methodOrConstructor + "] is neither a Method nor a Constructor");
}
return forExecutable((Executable) methodOrConstructor, parameterIndex);
return forExecutable(executable, parameterIndex);
}
/**
@@ -808,11 +808,11 @@ public class MethodParameter {
* @since 5.0
*/
public static MethodParameter forExecutable(Executable executable, int parameterIndex) {
if (executable instanceof Method) {
return new MethodParameter((Method) executable, parameterIndex);
if (executable instanceof Method method) {
return new MethodParameter(method, parameterIndex);
}
else if (executable instanceof Constructor) {
return new MethodParameter((Constructor<?>) executable, parameterIndex);
else if (executable instanceof Constructor<?> constructor) {
return new MethodParameter(constructor, parameterIndex);
}
else {
throw new IllegalArgumentException("Not a Method/Constructor: " + executable);

View File

@@ -118,8 +118,8 @@ public abstract class NestedCheckedException extends Exception {
if (cause == this) {
return false;
}
if (cause instanceof NestedCheckedException) {
return ((NestedCheckedException) cause).contains(exType);
if (cause instanceof NestedCheckedException exception) {
return exception.contains(exType);
}
else {
while (cause != null) {

View File

@@ -119,8 +119,8 @@ public abstract class NestedRuntimeException extends RuntimeException {
if (cause == this) {
return false;
}
if (cause instanceof NestedRuntimeException) {
return ((NestedRuntimeException) cause).contains(exType);
if (cause instanceof NestedRuntimeException exception) {
return exception.contains(exType);
}
else {
while (cause != null) {

View File

@@ -197,11 +197,11 @@ public class OrderComparator implements Comparator<Object> {
* @see java.util.Arrays#sort(Object[], java.util.Comparator)
*/
public static void sortIfNecessary(Object value) {
if (value instanceof Object[]) {
sort((Object[]) value);
if (value instanceof Object[] objects) {
sort(objects);
}
else if (value instanceof List) {
sort((List<?>) value);
else if (value instanceof List<?> list) {
sort(list);
}
}

View File

@@ -212,8 +212,8 @@ public class ResolvableType implements Serializable {
return this.resolved;
}
Type rawType = this.type;
if (rawType instanceof ParameterizedType) {
rawType = ((ParameterizedType) rawType).getRawType();
if (rawType instanceof ParameterizedType parameterizedType) {
rawType = parameterizedType.getRawType();
}
return (rawType instanceof Class ? (Class<?>) rawType : null);
}
@@ -314,8 +314,7 @@ public class ResolvableType implements Serializable {
boolean exactMatch = (matchedBefore != null); // We're checking nested generic variables now...
boolean checkGenerics = true;
Class<?> ourResolved = null;
if (this.type instanceof TypeVariable) {
TypeVariable<?> variable = (TypeVariable<?>) this.type;
if (this.type instanceof TypeVariable<?> variable) {
// Try default variable resolution
if (this.variableResolver != null) {
ResolvableType resolved = this.variableResolver.resolveVariable(variable);
@@ -394,12 +393,12 @@ public class ResolvableType implements Serializable {
if (this.componentType != null) {
return this.componentType;
}
if (this.type instanceof Class) {
Class<?> componentType = ((Class<?>) this.type).getComponentType();
if (this.type instanceof Class<?> clazz) {
Class<?> componentType = clazz.getComponentType();
return forType(componentType, this.variableResolver);
}
if (this.type instanceof GenericArrayType) {
return forType(((GenericArrayType) this.type).getGenericComponentType(), this.variableResolver);
if (this.type instanceof GenericArrayType genericArrayType) {
return forType(genericArrayType.getGenericComponentType(), this.variableResolver);
}
return resolveType().getComponentType();
}
@@ -556,8 +555,8 @@ public class ResolvableType implements Serializable {
if (resolved != null) {
try {
for (Type genericInterface : resolved.getGenericInterfaces()) {
if (genericInterface instanceof Class) {
if (forClass((Class<?>) genericInterface).hasGenerics()) {
if (genericInterface instanceof Class<?> clazz) {
if (forClass(clazz).hasGenerics()) {
return true;
}
}
@@ -576,11 +575,10 @@ public class ResolvableType implements Serializable {
* cannot be resolved through the associated variable resolver.
*/
private boolean isUnresolvableTypeVariable() {
if (this.type instanceof TypeVariable) {
if (this.type instanceof TypeVariable<?> variable) {
if (this.variableResolver == null) {
return true;
}
TypeVariable<?> variable = (TypeVariable<?>) this.type;
ResolvableType resolved = this.variableResolver.resolveVariable(variable);
if (resolved == null || resolved.isUnresolvableTypeVariable()) {
return true;
@@ -706,15 +704,15 @@ public class ResolvableType implements Serializable {
}
ResolvableType[] generics = this.generics;
if (generics == null) {
if (this.type instanceof Class) {
Type[] typeParams = ((Class<?>) this.type).getTypeParameters();
if (this.type instanceof Class<?> clazz) {
Type[] typeParams = clazz.getTypeParameters();
generics = new ResolvableType[typeParams.length];
for (int i = 0; i < generics.length; i++) {
generics[i] = ResolvableType.forType(typeParams[i], this);
}
}
else if (this.type instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) this.type).getActualTypeArguments();
else if (this.type instanceof ParameterizedType parameterizedType) {
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
generics = new ResolvableType[actualTypeArguments.length];
for (int i = 0; i < actualTypeArguments.length; i++) {
generics[i] = forType(actualTypeArguments[i], this.variableResolver);
@@ -815,8 +813,8 @@ public class ResolvableType implements Serializable {
if (this.type == EmptyType.INSTANCE) {
return null;
}
if (this.type instanceof Class) {
return (Class<?>) this.type;
if (this.type instanceof Class<?> clazz) {
return clazz;
}
if (this.type instanceof GenericArrayType) {
Class<?> resolvedComponent = getComponentType().resolve();
@@ -831,18 +829,17 @@ public class ResolvableType implements Serializable {
* as it cannot be serialized.
*/
ResolvableType resolveType() {
if (this.type instanceof ParameterizedType) {
return forType(((ParameterizedType) this.type).getRawType(), this.variableResolver);
if (this.type instanceof ParameterizedType parameterizedType) {
return forType(parameterizedType.getRawType(), this.variableResolver);
}
if (this.type instanceof WildcardType) {
Type resolved = resolveBounds(((WildcardType) this.type).getUpperBounds());
if (this.type instanceof WildcardType wildcardType) {
Type resolved = resolveBounds(wildcardType.getUpperBounds());
if (resolved == null) {
resolved = resolveBounds(((WildcardType) this.type).getLowerBounds());
resolved = resolveBounds(wildcardType.getLowerBounds());
}
return forType(resolved, this.variableResolver);
}
if (this.type instanceof TypeVariable) {
TypeVariable<?> variable = (TypeVariable<?>) this.type;
if (this.type instanceof TypeVariable<?> variable) {
// Try default variable resolution
if (this.variableResolver != null) {
ResolvableType resolved = this.variableResolver.resolveVariable(variable);
@@ -1106,8 +1103,8 @@ public class ResolvableType implements Serializable {
*/
public static ResolvableType forInstance(Object instance) {
Assert.notNull(instance, "Instance must not be null");
if (instance instanceof ResolvableTypeProvider) {
ResolvableType type = ((ResolvableTypeProvider) instance).getResolvableType();
if (instance instanceof ResolvableTypeProvider resolvableTypeProvider) {
ResolvableType type = resolvableTypeProvider.getResolvableType();
if (type != null) {
return type;
}

View File

@@ -91,8 +91,8 @@ final class SerializableTypeWrapper {
@SuppressWarnings("unchecked")
public static <T extends Type> T unwrap(T type) {
Type unwrapped = null;
if (type instanceof SerializableTypeProxy) {
unwrapped = ((SerializableTypeProxy) type).getTypeProvider().getType();
if (type instanceof SerializableTypeProxy proxy) {
unwrapped = proxy.getTypeProvider().getType();
}
return (unwrapped != null ? (T) unwrapped : type);
}
@@ -190,8 +190,8 @@ final class SerializableTypeWrapper {
case "equals":
Object other = args[0];
// Unwrap proxies for speed
if (other instanceof Type) {
other = unwrap((Type) other);
if (other instanceof Type otherType) {
other = unwrap(otherType);
}
return ObjectUtils.nullSafeEquals(this.provider.getType(), other);
case "hashCode":

View File

@@ -1074,8 +1074,8 @@ public abstract class AnnotationUtils {
* @param ex the throwable to inspect
*/
static void rethrowAnnotationConfigurationException(Throwable ex) {
if (ex instanceof AnnotationConfigurationException) {
throw (AnnotationConfigurationException) ex;
if (ex instanceof AnnotationConfigurationException exception) {
throw exception;
}
}

View File

@@ -55,8 +55,8 @@ public class NettyByteBufDecoder extends AbstractDataBufferDecoder<ByteBuf> {
if (logger.isDebugEnabled()) {
logger.debug(Hints.getLogPrefix(hints) + "Read " + dataBuffer.readableByteCount() + " bytes");
}
if (dataBuffer instanceof NettyDataBuffer) {
return ((NettyDataBuffer) dataBuffer).getNativeBuffer();
if (dataBuffer instanceof NettyDataBuffer nettyDataBuffer) {
return nettyDataBuffer.getNativeBuffer();
}
ByteBuf byteBuf;
byte[] bytes = new byte[dataBuffer.readableByteCount()];

View File

@@ -66,8 +66,8 @@ public class NettyByteBufEncoder extends AbstractEncoder<ByteBuf> {
String logPrefix = Hints.getLogPrefix(hints);
logger.debug(logPrefix + "Writing " + byteBuf.readableBytes() + " bytes");
}
if (bufferFactory instanceof NettyDataBufferFactory) {
return ((NettyDataBufferFactory) bufferFactory).wrap(byteBuf);
if (bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
return nettyDataBufferFactory.wrap(byteBuf);
}
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);

View File

@@ -48,14 +48,14 @@ public final class ConversionServiceFactory {
public static void registerConverters(@Nullable Set<?> converters, ConverterRegistry registry) {
if (converters != null) {
for (Object converter : converters) {
if (converter instanceof GenericConverter) {
registry.addConverter((GenericConverter) converter);
if (converter instanceof GenericConverter genericConverter) {
registry.addConverter(genericConverter);
}
else if (converter instanceof Converter<?, ?>) {
registry.addConverter((Converter<?, ?>) converter);
else if (converter instanceof Converter<?, ?> iConverter) {
registry.addConverter(iConverter);
}
else if (converter instanceof ConverterFactory<?, ?>) {
registry.addConverterFactory((ConverterFactory<?, ?>) converter);
else if (converter instanceof ConverterFactory<?, ?> converterFactory) {
registry.addConverterFactory(converterFactory);
}
else {
throw new IllegalArgumentException("Each converter object must implement one of the " +

View File

@@ -110,8 +110,8 @@ public class GenericConversionService implements ConfigurableConversionService {
@Override
public void addConverterFactory(ConverterFactory<?, ?> factory) {
ResolvableType[] typeInfo = getRequiredTypeInfo(factory.getClass(), ConverterFactory.class);
if (typeInfo == null && factory instanceof DecoratingProxy) {
typeInfo = getRequiredTypeInfo(((DecoratingProxy) factory).getDecoratedClass(), ConverterFactory.class);
if (typeInfo == null && factory instanceof DecoratingProxy proxy) {
typeInfo = getRequiredTypeInfo(proxy.getDecoratedClass(), ConverterFactory.class);
}
if (typeInfo == null) {
throw new IllegalArgumentException("Unable to determine source type <S> and target type <T> for your " +
@@ -373,8 +373,8 @@ public class GenericConversionService implements ConfigurableConversionService {
!this.targetType.hasUnresolvableGenerics()) {
return false;
}
return !(this.converter instanceof ConditionalConverter) ||
((ConditionalConverter) this.converter).matches(sourceType, targetType);
return !(this.converter instanceof ConditionalConverter converter) ||
converter.matches(sourceType, targetType);
}
@Override
@@ -416,13 +416,13 @@ public class GenericConversionService implements ConfigurableConversionService {
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
boolean matches = true;
if (this.converterFactory instanceof ConditionalConverter) {
matches = ((ConditionalConverter) this.converterFactory).matches(sourceType, targetType);
if (this.converterFactory instanceof ConditionalConverter conditionalConverter) {
matches = conditionalConverter.matches(sourceType, targetType);
}
if (matches) {
Converter<?, ?> converter = this.converterFactory.getConverter(targetType.getType());
if (converter instanceof ConditionalConverter) {
matches = ((ConditionalConverter) converter).matches(sourceType, targetType);
if (converter instanceof ConditionalConverter conditionalConverter) {
matches = conditionalConverter.matches(sourceType, targetType);
}
}
return matches;
@@ -659,8 +659,8 @@ public class GenericConversionService implements ConfigurableConversionService {
@Nullable
public GenericConverter getConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
for (GenericConverter converter : this.converters) {
if (!(converter instanceof ConditionalGenericConverter) ||
((ConditionalGenericConverter) converter).matches(sourceType, targetType)) {
if (!(converter instanceof ConditionalGenericConverter genericConverter) ||
genericConverter.matches(sourceType, targetType)) {
return converter;
}
}

View File

@@ -101,8 +101,7 @@ final class ObjectToObjectConverter implements ConditionalGenericConverter {
return method.invoke(null, source);
}
}
else if (member instanceof Constructor) {
Constructor<?> ctor = (Constructor<?>) member;
else if (member instanceof Constructor<?> ctor) {
ReflectionUtils.makeAccessible(ctor);
return ctor.newInstance(source);
}
@@ -156,8 +155,7 @@ final class ObjectToObjectConverter implements ConditionalGenericConverter {
ClassUtils.isAssignable(method.getDeclaringClass(), sourceClass) :
method.getParameterTypes()[0] == sourceClass);
}
else if (member instanceof Constructor) {
Constructor<?> ctor = (Constructor<?>) member;
else if (member instanceof Constructor<?> ctor) {
return (ctor.getParameterTypes()[0] == sourceClass);
}
else {

View File

@@ -84,8 +84,8 @@ public class PropertySourcesPropertyResolver extends AbstractPropertyResolver {
}
Object value = propertySource.getProperty(key);
if (value != null) {
if (resolveNestedPlaceholders && value instanceof String) {
value = resolveNestedPlaceholders((String) value);
if (resolveNestedPlaceholders && value instanceof String string) {
value = resolveNestedPlaceholders(string);
}
logKeyFound(key, propertySource, value);
return convertValueIfNecessary(value, targetValueType);

View File

@@ -288,8 +288,8 @@ public abstract class AbstractFileResolvingResource extends AbstractResource {
*/
protected void customizeConnection(URLConnection con) throws IOException {
ResourceUtils.useCachesIfNecessary(con);
if (con instanceof HttpURLConnection) {
customizeConnection((HttpURLConnection) con);
if (con instanceof HttpURLConnection httpConn) {
customizeConnection(httpConn);
}
}

View File

@@ -232,8 +232,8 @@ public class UrlResource extends AbstractFileResolvingResource {
}
catch (IOException ex) {
// Close the HTTP connection (if applicable).
if (con instanceof HttpURLConnection) {
((HttpURLConnection) con).disconnect();
if (con instanceof HttpURLConnection httpConn) {
httpConn.disconnect();
}
throw ex;
}
@@ -337,8 +337,8 @@ public class UrlResource extends AbstractFileResolvingResource {
*/
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof UrlResource &&
getCleanedUrl().equals(((UrlResource) other).getCleanedUrl())));
return (this == other || (other instanceof UrlResource resource &&
getCleanedUrl().equals(resource.getCleanedUrl())));
}
/**

View File

@@ -103,8 +103,8 @@ public abstract class VfsUtils {
}
catch (InvocationTargetException ex) {
Throwable targetEx = ex.getTargetException();
if (targetEx instanceof IOException) {
throw (IOException) targetEx;
if (targetEx instanceof IOException exception) {
throw exception;
}
ReflectionUtils.handleInvocationTargetException(ex);
}

View File

@@ -480,8 +480,8 @@ public abstract class DataBufferUtils {
*/
@SuppressWarnings("unchecked")
public static <T extends DataBuffer> T retain(T dataBuffer) {
if (dataBuffer instanceof PooledDataBuffer) {
return (T) ((PooledDataBuffer) dataBuffer).retain();
if (dataBuffer instanceof PooledDataBuffer buffer) {
return (T) buffer.retain();
}
else {
return dataBuffer;
@@ -498,8 +498,8 @@ public abstract class DataBufferUtils {
*/
@SuppressWarnings("unchecked")
public static <T extends DataBuffer> T touch(T dataBuffer, Object hint) {
if (dataBuffer instanceof PooledDataBuffer) {
return (T) ((PooledDataBuffer) dataBuffer).touch(hint);
if (dataBuffer instanceof PooledDataBuffer buffer) {
return (T) buffer.touch(hint);
}
else {
return dataBuffer;
@@ -568,12 +568,12 @@ public abstract class DataBufferUtils {
* @throws DataBufferLimitException if maxByteCount is exceeded
* @since 5.1.11
*/
@SuppressWarnings("unchecked")
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Mono<DataBuffer> join(Publisher<? extends DataBuffer> buffers, int maxByteCount) {
Assert.notNull(buffers, "'dataBuffers' must not be null");
if (buffers instanceof Mono) {
return (Mono<DataBuffer>) buffers;
if (buffers instanceof Mono mono) {
return mono;
}
return Flux.from(buffers)

View File

@@ -122,8 +122,8 @@ public class NettyDataBufferFactory implements DataBufferFactory {
* @return the netty {@code ByteBuf}
*/
public static ByteBuf toByteBuf(DataBuffer buffer) {
if (buffer instanceof NettyDataBuffer) {
return ((NettyDataBuffer) buffer).getNativeBuffer();
if (buffer instanceof NettyDataBuffer nettyDataBuffer) {
return nettyDataBuffer.getNativeBuffer();
}
else {
return Unpooled.wrappedBuffer(buffer.asByteBuffer());

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");
* you may not use this file except in compliance with the License.

View File

@@ -59,8 +59,8 @@ public abstract class ResourcePatternUtils {
* @see PathMatchingResourcePatternResolver
*/
public static ResourcePatternResolver getResourcePatternResolver(@Nullable ResourceLoader resourceLoader) {
if (resourceLoader instanceof ResourcePatternResolver) {
return (ResourcePatternResolver) resourceLoader;
if (resourceLoader instanceof ResourcePatternResolver resolver) {
return resolver;
}
else if (resourceLoader != null) {
return new PathMatchingResourcePatternResolver(resourceLoader);

View File

@@ -58,20 +58,20 @@ public class DefaultValueStyler implements ValueStyler {
else if (value instanceof String) {
return "\'" + value + "\'";
}
else if (value instanceof Class) {
return ClassUtils.getShortName((Class<?>) value);
else if (value instanceof Class<?> clazz) {
return ClassUtils.getShortName(clazz);
}
else if (value instanceof Method method) {
return method.getName() + "@" + ClassUtils.getShortName(method.getDeclaringClass());
}
else if (value instanceof Map) {
return style((Map<?, ?>) value);
else if (value instanceof Map<?, ?> map) {
return style(map);
}
else if (value instanceof Map.Entry) {
return style((Map.Entry<? ,?>) value);
else if (value instanceof Map.Entry<?, ?> entry) {
return style(entry);
}
else if (value instanceof Collection) {
return style((Collection<?>) value);
else if (value instanceof Collection<?> collection) {
return style(collection);
}
else if (value.getClass().isArray()) {
return styleArray(ObjectUtils.toObjectArray(value));

View File

@@ -106,8 +106,9 @@ public class TaskExecutorAdapter implements AsyncListenableTaskExecutor {
@Override
public Future<?> submit(Runnable task) {
try {
if (this.taskDecorator == null && this.concurrentExecutor instanceof ExecutorService) {
return ((ExecutorService) this.concurrentExecutor).submit(task);
if (this.taskDecorator == null &&
this.concurrentExecutor instanceof ExecutorService executor) {
return executor.submit(task);
}
else {
FutureTask<Object> future = new FutureTask<>(task, null);
@@ -124,8 +125,9 @@ public class TaskExecutorAdapter implements AsyncListenableTaskExecutor {
@Override
public <T> Future<T> submit(Callable<T> task) {
try {
if (this.taskDecorator == null && this.concurrentExecutor instanceof ExecutorService) {
return ((ExecutorService) this.concurrentExecutor).submit(task);
if (this.taskDecorator == null &&
this.concurrentExecutor instanceof ExecutorService executor) {
return executor.submit(task);
}
else {
FutureTask<T> future = new FutureTask<>(task);

View File

@@ -73,9 +73,8 @@ public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
*/
public CachingMetadataReaderFactory(@Nullable ResourceLoader resourceLoader) {
super(resourceLoader);
if (resourceLoader instanceof DefaultResourceLoader) {
this.metadataReaderCache =
((DefaultResourceLoader) resourceLoader).getResourceCache(MetadataReader.class);
if (resourceLoader instanceof DefaultResourceLoader loader) {
this.metadataReaderCache = loader.getResourceCache(MetadataReader.class);
}
else {
setCacheLimit(DEFAULT_CACHE_LIMIT);
@@ -93,8 +92,8 @@ public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
if (cacheLimit <= 0) {
this.metadataReaderCache = null;
}
else if (this.metadataReaderCache instanceof LocalResourceCache) {
((LocalResourceCache) this.metadataReaderCache).setCacheLimit(cacheLimit);
else if (this.metadataReaderCache instanceof LocalResourceCache cache) {
cache.setCacheLimit(cacheLimit);
}
else {
this.metadataReaderCache = new LocalResourceCache(cacheLimit);
@@ -105,8 +104,8 @@ public class CachingMetadataReaderFactory extends SimpleMetadataReaderFactory {
* Return the maximum number of entries for the MetadataReader cache.
*/
public int getCacheLimit() {
if (this.metadataReaderCache instanceof LocalResourceCache) {
return ((LocalResourceCache) this.metadataReaderCache).getCacheLimit();
if (this.metadataReaderCache instanceof LocalResourceCache cache) {
return cache.getCacheLimit();
}
else {
return (this.metadataReaderCache != null ? Integer.MAX_VALUE : 0);

View File

@@ -68,8 +68,8 @@ class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVis
@Override
public void visit(String name, Object value) {
if (value instanceof Type) {
value = ((Type) value).getClassName();
if (value instanceof Type typeObject) {
value = typeObject.getClassName();
}
this.attributes.put(name, value);
}
@@ -158,8 +158,8 @@ class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVis
@Override
public void visit(String name, Object value) {
if (value instanceof Type) {
value = ((Type) value).getClassName();
if (value instanceof Type typeObject) {
value = typeObject.getClassName();
}
this.elements.add(value);
}
@@ -187,8 +187,8 @@ class MergedAnnotationReadingVisitor<A extends Annotation> extends AnnotationVis
return Object.class;
}
Object firstElement = this.elements.get(0);
if (firstElement instanceof Enum) {
return ((Enum<?>) firstElement).getDeclaringClass();
if (firstElement instanceof Enum<?> enumObject) {
return enumObject.getDeclaringClass();
}
return firstElement.getClass();
}

View File

@@ -125,8 +125,8 @@ public abstract class DigestUtils {
private static byte[] digest(String algorithm, InputStream inputStream) throws IOException {
MessageDigest messageDigest = getDigest(algorithm);
if (inputStream instanceof UpdateMessageDigestInputStream){
((UpdateMessageDigestInputStream) inputStream).updateMessageDigest(messageDigest);
if (inputStream instanceof UpdateMessageDigestInputStream stream){
stream.updateMessageDigest(messageDigest);
return messageDigest.digest();
}
else {

View File

@@ -165,8 +165,8 @@ public class LinkedCaseInsensitiveMap<V> implements Map<String, V>, Serializable
@Override
@Nullable
public V get(Object key) {
if (key instanceof String) {
String caseInsensitiveKey = this.caseInsensitiveKeys.get(convertKey((String) key));
if (key instanceof String string) {
String caseInsensitiveKey = this.caseInsensitiveKeys.get(convertKey(string));
if (caseInsensitiveKey != null) {
return this.targetMap.get(caseInsensitiveKey);
}
@@ -177,8 +177,8 @@ public class LinkedCaseInsensitiveMap<V> implements Map<String, V>, Serializable
@Override
@Nullable
public V getOrDefault(Object key, V defaultValue) {
if (key instanceof String) {
String caseInsensitiveKey = this.caseInsensitiveKeys.get(convertKey((String) key));
if (key instanceof String string) {
String caseInsensitiveKey = this.caseInsensitiveKeys.get(convertKey(string));
if (caseInsensitiveKey != null) {
return this.targetMap.get(caseInsensitiveKey);
}
@@ -241,8 +241,8 @@ public class LinkedCaseInsensitiveMap<V> implements Map<String, V>, Serializable
@Override
@Nullable
public V remove(Object key) {
if (key instanceof String) {
String caseInsensitiveKey = removeCaseInsensitiveKey((String) key);
if (key instanceof String string) {
String caseInsensitiveKey = removeCaseInsensitiveKey(string);
if (caseInsensitiveKey != null) {
return this.targetMap.remove(caseInsensitiveKey);
}

View File

@@ -106,9 +106,9 @@ public abstract class NumberUtils {
return (T) Long.valueOf(value);
}
else if (BigInteger.class == targetClass) {
if (number instanceof BigDecimal) {
if (number instanceof BigDecimal bigDecimal) {
// do not lose precision - use BigDecimal's own conversion
return (T) ((BigDecimal) number).toBigInteger();
return (T) bigDecimal.toBigInteger();
}
else {
// original value is not a Big* number - use standard long conversion
@@ -143,11 +143,11 @@ public abstract class NumberUtils {
*/
private static long checkedLongValue(Number number, Class<? extends Number> targetClass) {
BigInteger bigInt = null;
if (number instanceof BigInteger) {
bigInt = (BigInteger) number;
if (number instanceof BigInteger bigInteger) {
bigInt = bigInteger;
}
else if (number instanceof BigDecimal) {
bigInt = ((BigDecimal) number).toBigInteger();
else if (number instanceof BigDecimal bigDecimal) {
bigInt = bigDecimal.toBigInteger();
}
// Effectively analogous to JDK 8's BigInteger.longValueExact()
if (bigInt != null && (bigInt.compareTo(LONG_MIN) < 0 || bigInt.compareTo(LONG_MAX) > 0)) {

View File

@@ -136,20 +136,20 @@ public abstract class ObjectUtils {
return true;
}
if (obj instanceof Optional) {
return !((Optional<?>) obj).isPresent();
if (obj instanceof Optional<?> optional) {
return !optional.isPresent();
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length() == 0;
if (obj instanceof CharSequence charSequence) {
return charSequence.length() == 0;
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof Collection) {
return ((Collection<?>) obj).isEmpty();
if (obj instanceof Collection<?> collection) {
return collection.isEmpty();
}
if (obj instanceof Map) {
return ((Map<?, ?>) obj).isEmpty();
if (obj instanceof Map<?, ?> map) {
return map.isEmpty();
}
// else
@@ -165,8 +165,7 @@ public abstract class ObjectUtils {
*/
@Nullable
public static Object unwrapOptional(@Nullable Object obj) {
if (obj instanceof Optional) {
Optional<?> optional = (Optional<?>) obj;
if (obj instanceof Optional<?> optional) {
if (!optional.isPresent()) {
return null;
}
@@ -291,8 +290,8 @@ public abstract class ObjectUtils {
* @throws IllegalArgumentException if the parameter is not an array
*/
public static Object[] toObjectArray(@Nullable Object source) {
if (source instanceof Object[]) {
return (Object[]) source;
if (source instanceof Object[] objects) {
return objects;
}
if (source == null) {
return EMPTY_OBJECT_ARRAY;
@@ -354,32 +353,32 @@ public abstract class ObjectUtils {
* @see java.util.Arrays#equals
*/
private static boolean arrayEquals(Object o1, Object o2) {
if (o1 instanceof Object[] && o2 instanceof Object[]) {
return Arrays.equals((Object[]) o1, (Object[]) o2);
if (o1 instanceof Object[] objects1 && o2 instanceof Object[] objects2) {
return Arrays.equals(objects1, objects2);
}
if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
return Arrays.equals((boolean[]) o1, (boolean[]) o2);
if (o1 instanceof boolean[] booleans1 && o2 instanceof boolean[] booleans2) {
return Arrays.equals(booleans1, booleans2);
}
if (o1 instanceof byte[] && o2 instanceof byte[]) {
return Arrays.equals((byte[]) o1, (byte[]) o2);
if (o1 instanceof byte[] bytes1 && o2 instanceof byte[] bytes2) {
return Arrays.equals(bytes1, bytes2);
}
if (o1 instanceof char[] && o2 instanceof char[]) {
return Arrays.equals((char[]) o1, (char[]) o2);
if (o1 instanceof char[] chars1 && o2 instanceof char[] chars2) {
return Arrays.equals(chars1, chars2);
}
if (o1 instanceof double[] && o2 instanceof double[]) {
return Arrays.equals((double[]) o1, (double[]) o2);
if (o1 instanceof double[] doubles1 && o2 instanceof double[] doubles2) {
return Arrays.equals(doubles1, doubles2);
}
if (o1 instanceof float[] && o2 instanceof float[]) {
return Arrays.equals((float[]) o1, (float[]) o2);
if (o1 instanceof float[] floats1 && o2 instanceof float[] floats2) {
return Arrays.equals(floats1, floats2);
}
if (o1 instanceof int[] && o2 instanceof int[]) {
return Arrays.equals((int[]) o1, (int[]) o2);
if (o1 instanceof int[] ints1 && o2 instanceof int[] ints2) {
return Arrays.equals(ints1, ints2);
}
if (o1 instanceof long[] && o2 instanceof long[]) {
return Arrays.equals((long[]) o1, (long[]) o2);
if (o1 instanceof long[] longs1 && o2 instanceof long[] longs2) {
return Arrays.equals(longs1, longs2);
}
if (o1 instanceof short[] && o2 instanceof short[]) {
return Arrays.equals((short[]) o1, (short[]) o2);
if (o1 instanceof short[] shorts1 && o2 instanceof short[] shorts2) {
return Arrays.equals(shorts1, shorts2);
}
return false;
}
@@ -406,32 +405,32 @@ public abstract class ObjectUtils {
return 0;
}
if (obj.getClass().isArray()) {
if (obj instanceof Object[]) {
return nullSafeHashCode((Object[]) obj);
if (obj instanceof Object[] objects) {
return nullSafeHashCode(objects);
}
if (obj instanceof boolean[]) {
return nullSafeHashCode((boolean[]) obj);
if (obj instanceof boolean[] booleans) {
return nullSafeHashCode(booleans);
}
if (obj instanceof byte[]) {
return nullSafeHashCode((byte[]) obj);
if (obj instanceof byte[] bytes) {
return nullSafeHashCode(bytes);
}
if (obj instanceof char[]) {
return nullSafeHashCode((char[]) obj);
if (obj instanceof char[] chars) {
return nullSafeHashCode(chars);
}
if (obj instanceof double[]) {
return nullSafeHashCode((double[]) obj);
if (obj instanceof double[] doubles) {
return nullSafeHashCode(doubles);
}
if (obj instanceof float[]) {
return nullSafeHashCode((float[]) obj);
if (obj instanceof float[] floats) {
return nullSafeHashCode(floats);
}
if (obj instanceof int[]) {
return nullSafeHashCode((int[]) obj);
if (obj instanceof int[] ints) {
return nullSafeHashCode(ints);
}
if (obj instanceof long[]) {
return nullSafeHashCode((long[]) obj);
if (obj instanceof long[] longs) {
return nullSafeHashCode(longs);
}
if (obj instanceof short[]) {
return nullSafeHashCode((short[]) obj);
if (obj instanceof short[] shorts) {
return nullSafeHashCode(shorts);
}
}
return obj.hashCode();
@@ -636,35 +635,35 @@ public abstract class ObjectUtils {
if (obj == null) {
return NULL_STRING;
}
if (obj instanceof String) {
return (String) obj;
if (obj instanceof String string) {
return string;
}
if (obj instanceof Object[]) {
return nullSafeToString((Object[]) obj);
if (obj instanceof Object[] objects) {
return nullSafeToString(objects);
}
if (obj instanceof boolean[]) {
return nullSafeToString((boolean[]) obj);
if (obj instanceof boolean[] booleans) {
return nullSafeToString(booleans);
}
if (obj instanceof byte[]) {
return nullSafeToString((byte[]) obj);
if (obj instanceof byte[] bytes) {
return nullSafeToString(bytes);
}
if (obj instanceof char[]) {
return nullSafeToString((char[]) obj);
if (obj instanceof char[] chars) {
return nullSafeToString(chars);
}
if (obj instanceof double[]) {
return nullSafeToString((double[]) obj);
if (obj instanceof double[] doubles) {
return nullSafeToString(doubles);
}
if (obj instanceof float[]) {
return nullSafeToString((float[]) obj);
if (obj instanceof float[] floats) {
return nullSafeToString(floats);
}
if (obj instanceof int[]) {
return nullSafeToString((int[]) obj);
if (obj instanceof int[] ints) {
return nullSafeToString(ints);
}
if (obj instanceof long[]) {
return nullSafeToString((long[]) obj);
if (obj instanceof long[] longs) {
return nullSafeToString(longs);
}
if (obj instanceof short[]) {
return nullSafeToString((short[]) obj);
if (obj instanceof short[] shorts) {
return nullSafeToString(shorts);
}
String str = obj.toString();
return (str != null ? str : EMPTY_STRING);

View File

@@ -106,11 +106,11 @@ public abstract class ReflectionUtils {
if (ex instanceof IllegalAccessException) {
throw new IllegalStateException("Could not access method or field: " + ex.getMessage());
}
if (ex instanceof InvocationTargetException) {
handleInvocationTargetException((InvocationTargetException) ex);
if (ex instanceof InvocationTargetException exception) {
handleInvocationTargetException(exception);
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
if (ex instanceof RuntimeException rex) {
throw rex;
}
throw new UndeclaredThrowableException(ex);
}
@@ -138,11 +138,11 @@ public abstract class ReflectionUtils {
* @throws RuntimeException the rethrown exception
*/
public static void rethrowRuntimeException(Throwable ex) {
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
if (ex instanceof RuntimeException rex) {
throw rex;
}
if (ex instanceof Error) {
throw (Error) ex;
if (ex instanceof Error error) {
throw error;
}
throw new UndeclaredThrowableException(ex);
}
@@ -159,11 +159,11 @@ public abstract class ReflectionUtils {
* @throws Exception the rethrown exception (in case of a checked exception)
*/
public static void rethrowException(Throwable ex) throws Exception {
if (ex instanceof Exception) {
throw (Exception) ex;
if (ex instanceof Exception e) {
throw e;
}
if (ex instanceof Error) {
throw (Error) ex;
if (ex instanceof Error error) {
throw error;
}
throw new UndeclaredThrowableException(ex);
}

View File

@@ -112,11 +112,11 @@ public class NullSafeComparator<T> implements Comparator<T> {
if (this == other) {
return true;
}
if (!(other instanceof NullSafeComparator)) {
if (!(other instanceof NullSafeComparator<?> nullSafeComparator)) {
return false;
}
NullSafeComparator<T> otherComp = (NullSafeComparator<T>) other;
return (this.nonNullComparator.equals(otherComp.nonNullComparator) && this.nullsLow == otherComp.nullsLow);
return this.nonNullComparator.equals(nullSafeComparator.nonNullComparator)
&& this.nullsLow == nullSafeComparator.nullsLow;
}
@Override

View File

@@ -50,8 +50,8 @@ class DomContentHandler implements ContentHandler {
*/
DomContentHandler(Node node) {
this.node = node;
if (node instanceof Document) {
this.document = (Document) node;
if (node instanceof Document document) {
this.document = document;
}
else {
this.document = node.getOwnerDocument();

View File

@@ -136,11 +136,11 @@ public abstract class StaxUtils {
*/
@Nullable
public static XMLStreamReader getXMLStreamReader(Source source) {
if (source instanceof StAXSource) {
return ((StAXSource) source).getXMLStreamReader();
if (source instanceof StAXSource stAXSource) {
return stAXSource.getXMLStreamReader();
}
else if (source instanceof StaxSource) {
return ((StaxSource) source).getXMLStreamReader();
else if (source instanceof StaxSource staxSource) {
return staxSource.getXMLStreamReader();
}
else {
throw new IllegalArgumentException("Source '" + source + "' is neither StaxSource nor StAXSource");
@@ -156,11 +156,11 @@ public abstract class StaxUtils {
*/
@Nullable
public static XMLEventReader getXMLEventReader(Source source) {
if (source instanceof StAXSource) {
return ((StAXSource) source).getXMLEventReader();
if (source instanceof StAXSource stAXSource) {
return stAXSource.getXMLEventReader();
}
else if (source instanceof StaxSource) {
return ((StaxSource) source).getXMLEventReader();
else if (source instanceof StaxSource staxSource) {
return staxSource.getXMLEventReader();
}
else {
throw new IllegalArgumentException("Source '" + source + "' is neither StaxSource nor StAXSource");
@@ -222,11 +222,11 @@ public abstract class StaxUtils {
*/
@Nullable
public static XMLStreamWriter getXMLStreamWriter(Result result) {
if (result instanceof StAXResult) {
return ((StAXResult) result).getXMLStreamWriter();
if (result instanceof StAXResult stAXResult) {
return stAXResult.getXMLStreamWriter();
}
else if (result instanceof StaxResult) {
return ((StaxResult) result).getXMLStreamWriter();
else if (result instanceof StaxResult staxResult) {
return staxResult.getXMLStreamWriter();
}
else {
throw new IllegalArgumentException("Result '" + result + "' is neither StaxResult nor StAXResult");
@@ -242,11 +242,11 @@ public abstract class StaxUtils {
*/
@Nullable
public static XMLEventWriter getXMLEventWriter(Result result) {
if (result instanceof StAXResult) {
return ((StAXResult) result).getXMLEventWriter();
if (result instanceof StAXResult stAXResult) {
return stAXResult.getXMLEventWriter();
}
else if (result instanceof StaxResult) {
return ((StaxResult) result).getXMLEventWriter();
else if (result instanceof StaxResult staxResult) {
return staxResult.getXMLEventWriter();
}
else {
throw new IllegalArgumentException("Result '" + result + "' is neither StaxResult nor StAXResult");