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) { public static Type resolveType(Type genericType, @Nullable Class<?> contextClass) {
if (contextClass != null) { if (contextClass != null) {
if (genericType instanceof TypeVariable) { if (genericType instanceof TypeVariable<?> typeVariable) {
ResolvableType resolvedTypeVariable = resolveVariable( ResolvableType resolvedTypeVariable = resolveVariable(
(TypeVariable<?>) genericType, ResolvableType.forClass(contextClass)); typeVariable, ResolvableType.forClass(contextClass));
if (resolvedTypeVariable != ResolvableType.NONE) { if (resolvedTypeVariable != ResolvableType.NONE) {
Class<?> resolved = resolvedTypeVariable.resolve(); Class<?> resolved = resolvedTypeVariable.resolve();
if (resolved != null) { 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); ResolvableType resolvedType = ResolvableType.forType(genericType);
if (resolvedType.hasUnresolvableGenerics()) { if (resolvedType.hasUnresolvableGenerics()) {
ParameterizedType parameterizedType = (ParameterizedType) genericType;
Class<?>[] generics = new Class<?>[parameterizedType.getActualTypeArguments().length]; Class<?>[] generics = new Class<?>[parameterizedType.getActualTypeArguments().length];
Type[] typeArguments = parameterizedType.getActualTypeArguments(); Type[] typeArguments = parameterizedType.getActualTypeArguments();
ResolvableType contextType = ResolvableType.forClass(contextClass); ResolvableType contextType = ResolvableType.forClass(contextClass);

View File

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

View File

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

View File

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

View File

@@ -197,11 +197,11 @@ public class OrderComparator implements Comparator<Object> {
* @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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -106,9 +106,9 @@ public abstract class NumberUtils {
return (T) Long.valueOf(value); return (T) Long.valueOf(value);
} }
else if (BigInteger.class == targetClass) { else if (BigInteger.class == targetClass) {
if (number instanceof BigDecimal) { if (number instanceof BigDecimal bigDecimal) {
// do not lose precision - use BigDecimal's own conversion // do not lose precision - use BigDecimal's own conversion
return (T) ((BigDecimal) number).toBigInteger(); return (T) bigDecimal.toBigInteger();
} }
else { else {
// original value is not a Big* number - use standard long conversion // 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) { private static long checkedLongValue(Number number, Class<? extends Number> targetClass) {
BigInteger bigInt = null; BigInteger bigInt = null;
if (number instanceof BigInteger) { if (number instanceof BigInteger bigInteger) {
bigInt = (BigInteger) number; bigInt = bigInteger;
} }
else if (number instanceof BigDecimal) { else if (number instanceof BigDecimal bigDecimal) {
bigInt = ((BigDecimal) number).toBigInteger(); bigInt = bigDecimal.toBigInteger();
} }
// Effectively analogous to JDK 8's BigInteger.longValueExact() // Effectively analogous to JDK 8's BigInteger.longValueExact()
if (bigInt != null && (bigInt.compareTo(LONG_MIN) < 0 || bigInt.compareTo(LONG_MAX) > 0)) { 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; return true;
} }
if (obj instanceof Optional) { if (obj instanceof Optional<?> optional) {
return !((Optional<?>) obj).isPresent(); return !optional.isPresent();
} }
if (obj instanceof CharSequence) { if (obj instanceof CharSequence charSequence) {
return ((CharSequence) obj).length() == 0; return charSequence.length() == 0;
} }
if (obj.getClass().isArray()) { if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0; return Array.getLength(obj) == 0;
} }
if (obj instanceof Collection) { if (obj instanceof Collection<?> collection) {
return ((Collection<?>) obj).isEmpty(); return collection.isEmpty();
} }
if (obj instanceof Map) { if (obj instanceof Map<?, ?> map) {
return ((Map<?, ?>) obj).isEmpty(); return map.isEmpty();
} }
// else // else
@@ -165,8 +165,7 @@ public abstract class ObjectUtils {
*/ */
@Nullable @Nullable
public static Object unwrapOptional(@Nullable Object obj) { public static Object unwrapOptional(@Nullable Object obj) {
if (obj instanceof Optional) { if (obj instanceof Optional<?> optional) {
Optional<?> optional = (Optional<?>) obj;
if (!optional.isPresent()) { if (!optional.isPresent()) {
return null; return null;
} }
@@ -291,8 +290,8 @@ public abstract class ObjectUtils {
* @throws IllegalArgumentException if the parameter is not an array * @throws IllegalArgumentException if the parameter is not an array
*/ */
public static Object[] toObjectArray(@Nullable Object source) { public static Object[] toObjectArray(@Nullable Object source) {
if (source instanceof Object[]) { if (source instanceof Object[] objects) {
return (Object[]) source; return objects;
} }
if (source == null) { if (source == null) {
return EMPTY_OBJECT_ARRAY; return EMPTY_OBJECT_ARRAY;
@@ -354,32 +353,32 @@ public abstract class ObjectUtils {
* @see java.util.Arrays#equals * @see java.util.Arrays#equals
*/ */
private static boolean arrayEquals(Object o1, Object o2) { private static boolean arrayEquals(Object o1, Object o2) {
if (o1 instanceof Object[] && o2 instanceof Object[]) { if (o1 instanceof Object[] objects1 && o2 instanceof Object[] objects2) {
return Arrays.equals((Object[]) o1, (Object[]) o2); return Arrays.equals(objects1, objects2);
} }
if (o1 instanceof boolean[] && o2 instanceof boolean[]) { if (o1 instanceof boolean[] booleans1 && o2 instanceof boolean[] booleans2) {
return Arrays.equals((boolean[]) o1, (boolean[]) o2); return Arrays.equals(booleans1, booleans2);
} }
if (o1 instanceof byte[] && o2 instanceof byte[]) { if (o1 instanceof byte[] bytes1 && o2 instanceof byte[] bytes2) {
return Arrays.equals((byte[]) o1, (byte[]) o2); return Arrays.equals(bytes1, bytes2);
} }
if (o1 instanceof char[] && o2 instanceof char[]) { if (o1 instanceof char[] chars1 && o2 instanceof char[] chars2) {
return Arrays.equals((char[]) o1, (char[]) o2); return Arrays.equals(chars1, chars2);
} }
if (o1 instanceof double[] && o2 instanceof double[]) { if (o1 instanceof double[] doubles1 && o2 instanceof double[] doubles2) {
return Arrays.equals((double[]) o1, (double[]) o2); return Arrays.equals(doubles1, doubles2);
} }
if (o1 instanceof float[] && o2 instanceof float[]) { if (o1 instanceof float[] floats1 && o2 instanceof float[] floats2) {
return Arrays.equals((float[]) o1, (float[]) o2); return Arrays.equals(floats1, floats2);
} }
if (o1 instanceof int[] && o2 instanceof int[]) { if (o1 instanceof int[] ints1 && o2 instanceof int[] ints2) {
return Arrays.equals((int[]) o1, (int[]) o2); return Arrays.equals(ints1, ints2);
} }
if (o1 instanceof long[] && o2 instanceof long[]) { if (o1 instanceof long[] longs1 && o2 instanceof long[] longs2) {
return Arrays.equals((long[]) o1, (long[]) o2); return Arrays.equals(longs1, longs2);
} }
if (o1 instanceof short[] && o2 instanceof short[]) { if (o1 instanceof short[] shorts1 && o2 instanceof short[] shorts2) {
return Arrays.equals((short[]) o1, (short[]) o2); return Arrays.equals(shorts1, shorts2);
} }
return false; return false;
} }
@@ -406,32 +405,32 @@ public abstract class ObjectUtils {
return 0; return 0;
} }
if (obj.getClass().isArray()) { if (obj.getClass().isArray()) {
if (obj instanceof Object[]) { if (obj instanceof Object[] objects) {
return nullSafeHashCode((Object[]) obj); return nullSafeHashCode(objects);
} }
if (obj instanceof boolean[]) { if (obj instanceof boolean[] booleans) {
return nullSafeHashCode((boolean[]) obj); return nullSafeHashCode(booleans);
} }
if (obj instanceof byte[]) { if (obj instanceof byte[] bytes) {
return nullSafeHashCode((byte[]) obj); return nullSafeHashCode(bytes);
} }
if (obj instanceof char[]) { if (obj instanceof char[] chars) {
return nullSafeHashCode((char[]) obj); return nullSafeHashCode(chars);
} }
if (obj instanceof double[]) { if (obj instanceof double[] doubles) {
return nullSafeHashCode((double[]) obj); return nullSafeHashCode(doubles);
} }
if (obj instanceof float[]) { if (obj instanceof float[] floats) {
return nullSafeHashCode((float[]) obj); return nullSafeHashCode(floats);
} }
if (obj instanceof int[]) { if (obj instanceof int[] ints) {
return nullSafeHashCode((int[]) obj); return nullSafeHashCode(ints);
} }
if (obj instanceof long[]) { if (obj instanceof long[] longs) {
return nullSafeHashCode((long[]) obj); return nullSafeHashCode(longs);
} }
if (obj instanceof short[]) { if (obj instanceof short[] shorts) {
return nullSafeHashCode((short[]) obj); return nullSafeHashCode(shorts);
} }
} }
return obj.hashCode(); return obj.hashCode();
@@ -636,35 +635,35 @@ public abstract class ObjectUtils {
if (obj == null) { if (obj == null) {
return NULL_STRING; return NULL_STRING;
} }
if (obj instanceof String) { if (obj instanceof String string) {
return (String) obj; return string;
} }
if (obj instanceof Object[]) { if (obj instanceof Object[] objects) {
return nullSafeToString((Object[]) obj); return nullSafeToString(objects);
} }
if (obj instanceof boolean[]) { if (obj instanceof boolean[] booleans) {
return nullSafeToString((boolean[]) obj); return nullSafeToString(booleans);
} }
if (obj instanceof byte[]) { if (obj instanceof byte[] bytes) {
return nullSafeToString((byte[]) obj); return nullSafeToString(bytes);
} }
if (obj instanceof char[]) { if (obj instanceof char[] chars) {
return nullSafeToString((char[]) obj); return nullSafeToString(chars);
} }
if (obj instanceof double[]) { if (obj instanceof double[] doubles) {
return nullSafeToString((double[]) obj); return nullSafeToString(doubles);
} }
if (obj instanceof float[]) { if (obj instanceof float[] floats) {
return nullSafeToString((float[]) obj); return nullSafeToString(floats);
} }
if (obj instanceof int[]) { if (obj instanceof int[] ints) {
return nullSafeToString((int[]) obj); return nullSafeToString(ints);
} }
if (obj instanceof long[]) { if (obj instanceof long[] longs) {
return nullSafeToString((long[]) obj); return nullSafeToString(longs);
} }
if (obj instanceof short[]) { if (obj instanceof short[] shorts) {
return nullSafeToString((short[]) obj); return nullSafeToString(shorts);
} }
String str = obj.toString(); String str = obj.toString();
return (str != null ? str : EMPTY_STRING); return (str != null ? str : EMPTY_STRING);

View File

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

View File

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

View File

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

View File

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