Apply "instanceof pattern matching" Eclipse clean-up in spring-context

This commit also applies additional clean-up tasks such as the following.

- final fields
- diamond operator (<>) for anonymous inner classes
- Comparator.comparing
- convert to switch expression

This has only been applied to `src/main/java`.
This commit is contained in:
Sam Brannen 2021-10-14 17:09:30 +02:00
parent 401c0d220a
commit 67333a3f94
46 changed files with 137 additions and 172 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 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.
@ -168,10 +168,9 @@ public class AnnotationCacheOperationSource extends AbstractFallbackCacheOperati
if (this == other) {
return true;
}
if (!(other instanceof AnnotationCacheOperationSource)) {
if (!(other instanceof AnnotationCacheOperationSource otherCos)) {
return false;
}
AnnotationCacheOperationSource otherCos = (AnnotationCacheOperationSource) other;
return (this.annotationParsers.equals(otherCos.annotationParsers) &&
this.publicMethodsOnly == otherCos.publicMethodsOnly);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 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.
@ -175,15 +175,15 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser {
*/
private static class Props {
private String key;
private final String key;
private String keyGenerator;
private final String keyGenerator;
private String cacheManager;
private final String cacheManager;
private String condition;
private final String condition;
private String method;
private final String method;
@Nullable
private String[] caches;

View File

@ -857,10 +857,9 @@ public abstract class CacheAspectSupport extends AbstractCacheInvoker
if (this == other) {
return true;
}
if (!(other instanceof CacheOperationCacheKey)) {
if (!(other instanceof CacheOperationCacheKey otherKey)) {
return false;
}
CacheOperationCacheKey otherKey = (CacheOperationCacheKey) other;
return (this.cacheOperation.equals(otherKey.cacheOperation) &&
this.methodCacheKey.equals(otherKey.methodCacheKey));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 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.
@ -53,10 +53,9 @@ abstract class CacheOperationSourcePointcut extends StaticMethodMatcherPointcut
if (this == other) {
return true;
}
if (!(other instanceof CacheOperationSourcePointcut)) {
if (!(other instanceof CacheOperationSourcePointcut otherPc)) {
return false;
}
CacheOperationSourcePointcut otherPc = (CacheOperationSourcePointcut) other;
return ObjectUtils.nullSafeEquals(getCacheOperationSource(), otherPc.getCacheOperationSource());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 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.
@ -47,7 +47,7 @@ public class NameMatchCacheOperationSource implements CacheOperationSource, Seri
/** Keys are method names; values are TransactionAttributes. */
private Map<String, Collection<CacheOperation>> nameMap = new LinkedHashMap<>();
private final Map<String, Collection<CacheOperation>> nameMap = new LinkedHashMap<>();
/**
@ -114,10 +114,9 @@ public class NameMatchCacheOperationSource implements CacheOperationSource, Seri
if (this == other) {
return true;
}
if (!(other instanceof NameMatchCacheOperationSource)) {
if (!(other instanceof NameMatchCacheOperationSource otherTas)) {
return false;
}
NameMatchCacheOperationSource otherTas = (NameMatchCacheOperationSource) other;
return ObjectUtils.nullSafeEquals(this.nameMap, otherTas.nameMap);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@ -107,8 +107,7 @@ public class AnnotationBeanNameGenerator implements BeanNameGenerator {
});
if (isStereotypeWithNameValue(type, metaTypes, attributes)) {
Object value = attributes.get("value");
if (value instanceof String) {
String strVal = (String) value;
if (value instanceof String strVal) {
if (StringUtils.hasLength(strVal)) {
if (beanName != null && !strVal.equals(beanName)) {
throw new IllegalStateException("Stereotype annotations suggest inconsistent " +

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2021 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.
@ -77,8 +77,7 @@ public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver {
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
ScopeMetadata metadata = new ScopeMetadata();
if (definition instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
if (definition instanceof AnnotatedBeanDefinition annDef) {
AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(
annDef.getMetadata(), this.scopeAnnotationType);
if (attributes != null) {

View File

@ -266,8 +266,8 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
if (this.resourceFactory == null) {
this.resourceFactory = beanFactory;
}
if (beanFactory instanceof ConfigurableBeanFactory) {
this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory);
if (beanFactory instanceof ConfigurableBeanFactory configurableBeanFactory) {
this.embeddedValueResolver = new EmbeddedValueResolver(configurableBeanFactory);
}
}
@ -437,8 +437,8 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
if (element.lookupType.isInterface()) {
pf.addInterface(element.lookupType);
}
ClassLoader classLoader = (this.beanFactory instanceof ConfigurableBeanFactory ?
((ConfigurableBeanFactory) this.beanFactory).getBeanClassLoader() : null);
ClassLoader classLoader = (this.beanFactory instanceof ConfigurableBeanFactory configurableBeanFactory ?
configurableBeanFactory.getBeanClassLoader() : null);
return pf.getProxy(classLoader);
}
@ -492,18 +492,17 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
Set<String> autowiredBeanNames;
String name = element.name;
if (factory instanceof AutowireCapableBeanFactory) {
AutowireCapableBeanFactory beanFactory = (AutowireCapableBeanFactory) factory;
if (factory instanceof AutowireCapableBeanFactory autowireCapableBeanFactory) {
DependencyDescriptor descriptor = element.getDependencyDescriptor();
if (this.fallbackToDefaultTypeMatch && element.isDefaultName && !factory.containsBean(name)) {
autowiredBeanNames = new LinkedHashSet<>();
resource = beanFactory.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, null);
resource = autowireCapableBeanFactory.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, null);
if (resource == null) {
throw new NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object");
}
}
else {
resource = beanFactory.resolveBeanByName(name, descriptor);
resource = autowireCapableBeanFactory.resolveBeanByName(name, descriptor);
autowiredBeanNames = Collections.singleton(name);
}
}
@ -512,11 +511,10 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
autowiredBeanNames = Collections.singleton(name);
}
if (factory instanceof ConfigurableBeanFactory) {
ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) factory;
if (factory instanceof ConfigurableBeanFactory configurableBeanFactory) {
for (String autowiredBeanName : autowiredBeanNames) {
if (requestingBeanName != null && beanFactory.containsBean(autowiredBeanName)) {
beanFactory.registerDependentBean(autowiredBeanName, requestingBeanName);
if (requestingBeanName != null && configurableBeanFactory.containsBean(autowiredBeanName)) {
configurableBeanFactory.registerDependentBean(autowiredBeanName, requestingBeanName);
}
}
}
@ -671,8 +669,8 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
if (beanFactory != null && beanFactory.containsBean(this.beanName)) {
// Local match found for explicitly specified local bean name.
Object bean = beanFactory.getBean(this.beanName, this.lookupType);
if (requestingBeanName != null && beanFactory instanceof ConfigurableBeanFactory) {
((ConfigurableBeanFactory) beanFactory).registerDependentBean(this.beanName, requestingBeanName);
if (requestingBeanName != null && beanFactory instanceof ConfigurableBeanFactory configurableBeanFactory) {
configurableBeanFactory.registerDependentBean(this.beanName, requestingBeanName);
}
return bean;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@ -305,8 +305,7 @@ class ConfigurationClassBeanDefinitionReader {
// -> allow the current bean method to override, since both are at second-pass level.
// However, if the bean method is an overloaded case on the same configuration class,
// preserve the existing bean definition.
if (existingBeanDef instanceof ConfigurationClassBeanDefinition) {
ConfigurationClassBeanDefinition ccbd = (ConfigurationClassBeanDefinition) existingBeanDef;
if (existingBeanDef instanceof ConfigurationClassBeanDefinition ccbd) {
if (ccbd.getMetadata().getClassName().equals(
beanMethod.getConfigurationClass().getMetadata().getClassName())) {
if (ccbd.getFactoryMethodMetadata().getMethodName().equals(ccbd.getFactoryMethodName())) {
@ -373,8 +372,7 @@ class ConfigurationClassBeanDefinitionReader {
// Instantiate the specified BeanDefinitionReader
reader = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry);
// Delegate the current ResourceLoader to it if possible
if (reader instanceof AbstractBeanDefinitionReader) {
AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) reader);
if (reader instanceof AbstractBeanDefinitionReader abdr) {
abdr.setResourceLoader(this.resourceLoader);
abdr.setEnvironment(this.environment);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 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.
@ -26,6 +26,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.scope.ScopedProxyFactoryBean;
import org.springframework.asm.Opcodes;
import org.springframework.asm.Type;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
@ -36,7 +37,6 @@ import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.support.SimpleInstantiationStrategy;
import org.springframework.cglib.core.ClassGenerator;
import org.springframework.cglib.core.ClassLoaderAwareGeneratorStrategy;
import org.springframework.cglib.core.Constants;
import org.springframework.cglib.core.SpringNamingPolicy;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.CallbackFilter;
@ -219,7 +219,7 @@ class ConfigurationClassEnhancer {
ClassEmitterTransformer transformer = new ClassEmitterTransformer() {
@Override
public void end_class() {
declare_field(Constants.ACC_PUBLIC, BEAN_FACTORY_FIELD, Type.getType(BeanFactory.class), null);
declare_field(Opcodes.ACC_PUBLIC, BEAN_FACTORY_FIELD, Type.getType(BeanFactory.class), null);
super.end_class();
}
};

View File

@ -371,10 +371,10 @@ public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPo
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory cachingMetadataReaderFactory) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
cachingMetadataReaderFactory.clearCache();
}
}
@ -392,33 +392,30 @@ public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPo
Object configClassAttr = beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE);
AnnotationMetadata annotationMetadata = null;
MethodMetadata methodMetadata = null;
if (beanDef instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDef;
if (beanDef instanceof AnnotatedBeanDefinition annotatedBeanDefinition) {
annotationMetadata = annotatedBeanDefinition.getMetadata();
methodMetadata = annotatedBeanDefinition.getFactoryMethodMetadata();
}
if ((configClassAttr != null || methodMetadata != null) && beanDef instanceof AbstractBeanDefinition) {
if ((configClassAttr != null || methodMetadata != null) &&
(beanDef instanceof AbstractBeanDefinition abd) && !abd.hasBeanClass()) {
// Configuration class (full or lite) or a configuration-derived @Bean method
// -> eagerly resolve bean class at this point, unless it's a 'lite' configuration
// or component class without @Bean methods.
AbstractBeanDefinition abd = (AbstractBeanDefinition) beanDef;
if (!abd.hasBeanClass()) {
boolean liteConfigurationCandidateWithoutBeanMethods =
(ConfigurationClassUtils.CONFIGURATION_CLASS_LITE.equals(configClassAttr) &&
annotationMetadata != null && !ConfigurationClassUtils.hasBeanMethods(annotationMetadata));
if (!liteConfigurationCandidateWithoutBeanMethods) {
try {
abd.resolveBeanClass(this.beanClassLoader);
}
catch (Throwable ex) {
throw new IllegalStateException(
"Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
}
boolean liteConfigurationCandidateWithoutBeanMethods =
(ConfigurationClassUtils.CONFIGURATION_CLASS_LITE.equals(configClassAttr) &&
annotationMetadata != null && !ConfigurationClassUtils.hasBeanMethods(annotationMetadata));
if (!liteConfigurationCandidateWithoutBeanMethods) {
try {
abd.resolveBeanClass(this.beanClassLoader);
}
catch (Throwable ex) {
throw new IllegalStateException(
"Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
}
}
}
if (ConfigurationClassUtils.CONFIGURATION_CLASS_FULL.equals(configClassAttr)) {
if (!(beanDef instanceof AbstractBeanDefinition)) {
if (!(beanDef instanceof AbstractBeanDefinition abd)) {
throw new BeanDefinitionStoreException("Cannot enhance @Configuration bean definition '" +
beanName + "' since it is not stored in an AbstractBeanDefinition subclass");
}
@ -428,7 +425,7 @@ public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPo
"is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor " +
"return type: Consider declaring such methods as 'static'.");
}
configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
configBeanDefs.put(beanName, abd);
}
}
if (configBeanDefs.isEmpty() || NativeDetector.inNativeImage()) {
@ -469,19 +466,19 @@ public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPo
public PropertyValues postProcessProperties(@Nullable PropertyValues pvs, Object bean, String beanName) {
// Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's
// postProcessProperties method attempts to autowire other configuration beans.
if (bean instanceof EnhancedConfiguration) {
((EnhancedConfiguration) bean).setBeanFactory(this.beanFactory);
if (bean instanceof EnhancedConfiguration enhancedConfiguration) {
enhancedConfiguration.setBeanFactory(this.beanFactory);
}
return pvs;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if (bean instanceof ImportAware) {
if (bean instanceof ImportAware importAware) {
ImportRegistry ir = this.beanFactory.getBean(IMPORT_REGISTRY_BEAN_NAME, ImportRegistry.class);
AnnotationMetadata importingClass = ir.getImportingClassFor(ClassUtils.getUserClass(bean).getName());
if (importingClass != null) {
((ImportAware) bean).setImportMetadata(importingClass);
importAware.setImportMetadata(importingClass);
}
}
return bean;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2021 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.
@ -87,8 +87,7 @@ public class Jsr330ScopeMetadataResolver implements ScopeMetadataResolver {
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
ScopeMetadata metadata = new ScopeMetadata();
metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
if (definition instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
if (definition instanceof AnnotatedBeanDefinition annDef) {
Set<String> annTypes = annDef.getMetadata().getAnnotationTypes();
String found = null;
for (String annType : annTypes) {

View File

@ -400,10 +400,9 @@ public abstract class AbstractApplicationEventMulticaster
if (this == other) {
return true;
}
if (!(other instanceof ListenerCacheKey)) {
if (!(other instanceof ListenerCacheKey otherKey)) {
return false;
}
ListenerCacheKey otherKey = (ListenerCacheKey) other;
return (this.eventType.equals(otherKey.eventType) &&
ObjectUtils.nullSafeEquals(this.sourceType, otherKey.sourceType));
}

View File

@ -293,8 +293,7 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe
publishEvent(event);
}
}
else if (result instanceof Collection<?>) {
Collection<?> events = (Collection<?>) result;
else if (result instanceof Collection<?> events) {
for (Object event : events) {
publishEvent(event);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2021 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.
@ -55,10 +55,9 @@ public final class AnnotatedElementKey implements Comparable<AnnotatedElementKey
if (this == other) {
return true;
}
if (!(other instanceof AnnotatedElementKey)) {
if (!(other instanceof AnnotatedElementKey otherKey)) {
return false;
}
AnnotatedElementKey otherKey = (AnnotatedElementKey) other;
return (this.element.equals(otherKey.element) &&
ObjectUtils.nullSafeEquals(this.targetClass, otherKey.targetClass));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 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.
@ -118,10 +118,9 @@ public abstract class CachedExpressionEvaluator {
if (this == other) {
return true;
}
if (!(other instanceof ExpressionKey)) {
if (!(other instanceof ExpressionKey otherKey)) {
return false;
}
ExpressionKey otherKey = (ExpressionKey) other;
return (this.element.equals(otherKey.element) &&
ObjectUtils.nullSafeEquals(this.expression, otherKey.expression));
}

View File

@ -211,7 +211,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
private Thread shutdownHook;
/** ResourcePatternResolver used by this context. */
private ResourcePatternResolver resourcePatternResolver;
private final ResourcePatternResolver resourcePatternResolver;
/** LifecycleProcessor for managing the lifecycle of beans within this context. */
@Nullable
@ -771,8 +771,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource hms) {
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 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.
@ -174,10 +174,9 @@ public class DefaultMessageSourceResolvable implements MessageSourceResolvable,
if (this == other) {
return true;
}
if (!(other instanceof MessageSourceResolvable)) {
if (!(other instanceof MessageSourceResolvable otherResolvable)) {
return false;
}
MessageSourceResolvable otherResolvable = (MessageSourceResolvable) other;
return (ObjectUtils.nullSafeEquals(getCodes(), otherResolvable.getCodes()) &&
ObjectUtils.nullSafeEquals(getArguments(), otherResolvable.getArguments()) &&
ObjectUtils.nullSafeEquals(getDefaultMessage(), otherResolvable.getDefaultMessage()));

View File

@ -35,7 +35,6 @@ import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
@ -75,15 +74,12 @@ final class PostProcessorRegistrationDelegate {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
if (beanFactory instanceof BeanDefinitionRegistry registry) {
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor registryProcessor) {
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
@ -384,7 +380,7 @@ final class PostProcessorRegistrationDelegate {
private boolean isInfrastructureBean(@Nullable String beanName) {
if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
return (bd.getRole() == BeanDefinition.ROLE_INFRASTRUCTURE);
}
return false;
}

View File

@ -130,7 +130,7 @@ public class PropertySourcesPlaceholderConfigurer extends PlaceholderConfigurerS
this.propertySources = new MutablePropertySources();
if (this.environment != null) {
this.propertySources.addLast(
new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
new PropertySource<>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
@Override
@Nullable
public String getProperty(String key) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@ -56,7 +56,7 @@ public class SimpleThreadScope implements Scope {
private static final Log logger = LogFactory.getLog(SimpleThreadScope.class);
private final ThreadLocal<Map<String, Object>> threadScope =
new NamedThreadLocal<Map<String, Object>>("SimpleThreadScope") {
new NamedThreadLocal<>("SimpleThreadScope") {
@Override
protected Map<String, Object> initialValue() {
return new HashMap<>();

View File

@ -183,6 +183,15 @@ public class DateTimeFormatterFactory {
dateTimeFormatter = DateTimeFormatterUtils.createStrictDateTimeFormatter(this.pattern);
}
else if (this.iso != null && this.iso != ISO.NONE) {
// TODO Use switch expression once spring-javaformat 0.0.30 has been released.
// See https://github.com/spring-io/spring-javaformat/issues/300
//
// dateTimeFormatter = switch (this.iso) {
// case DATE -> DateTimeFormatter.ISO_DATE;
// case TIME -> DateTimeFormatter.ISO_TIME;
// case DATE_TIME -> DateTimeFormatter.ISO_DATE_TIME;
// default -> throw new IllegalStateException("Unsupported ISO format: " + this.iso);
// };
switch (this.iso) {
case DATE:
dateTimeFormatter = DateTimeFormatter.ISO_DATE;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2021 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.
@ -71,13 +71,12 @@ public class NumberStyleFormatter extends AbstractNumberFormatter {
@Override
public NumberFormat getNumberFormat(Locale locale) {
NumberFormat format = NumberFormat.getInstance(locale);
if (!(format instanceof DecimalFormat)) {
if (!(format instanceof DecimalFormat decimalFormat)) {
if (this.pattern != null) {
throw new IllegalStateException("Cannot support pattern for non-DecimalFormat: " + format);
}
return format;
}
DecimalFormat decimalFormat = (DecimalFormat) format;
decimalFormat.setParseBigDecimal(true);
if (this.pattern != null) {
decimalFormat.applyPattern(this.pattern);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 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.
@ -370,10 +370,9 @@ public class FormattingConversionService extends GenericConversionService
if (this == other) {
return true;
}
if (!(other instanceof AnnotationConverterKey)) {
if (!(other instanceof AnnotationConverterKey otherKey)) {
return false;
}
AnnotationConverterKey otherKey = (AnnotationConverterKey) other;
return (this.fieldType == otherKey.fieldType && this.annotation.equals(otherKey.annotation));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 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.
@ -36,7 +36,7 @@ import org.springframework.util.Assert;
*/
public class ResourceOverridingShadowingClassLoader extends ShadowingClassLoader {
private static final Enumeration<URL> EMPTY_URL_ENUMERATION = new Enumeration<URL>() {
private static final Enumeration<URL> EMPTY_URL_ENUMERATION = new Enumeration<>() {
@Override
public boolean hasMoreElements() {
return false;
@ -51,7 +51,7 @@ public class ResourceOverridingShadowingClassLoader extends ShadowingClassLoader
/**
* Key is asked for value: value is actual value.
*/
private Map<String, String> overrides = new HashMap<>();
private final Map<String, String> overrides = new HashMap<>();
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@ -566,8 +566,7 @@ public class MBeanClientInterceptor
Method fromMethod = targetClass.getMethod("from", CompositeData.class);
return ReflectionUtils.invokeMethod(fromMethod, null, result);
}
else if (result instanceof CompositeData[]) {
CompositeData[] array = (CompositeData[]) result;
else if (result instanceof CompositeData[] array) {
if (targetClass.isArray()) {
return convertDataArrayToTargetArray(array, targetClass);
}
@ -583,8 +582,7 @@ public class MBeanClientInterceptor
Method fromMethod = targetClass.getMethod("from", TabularData.class);
return ReflectionUtils.invokeMethod(fromMethod, null, result);
}
else if (result instanceof TabularData[]) {
TabularData[] array = (TabularData[]) result;
else if (result instanceof TabularData[] array) {
if (targetClass.isArray()) {
return convertDataArrayToTargetArray(array, targetClass);
}
@ -621,8 +619,8 @@ public class MBeanClientInterceptor
Method fromMethod = elementType.getMethod("from", array.getClass().getComponentType());
Collection<Object> resultColl = CollectionFactory.createCollection(collectionType, Array.getLength(array));
for (int i = 0; i < array.length; i++) {
resultColl.add(ReflectionUtils.invokeMethod(fromMethod, null, array[i]));
for (Object element : array) {
resultColl.add(ReflectionUtils.invokeMethod(fromMethod, null, element));
}
return resultColl;
}
@ -660,10 +658,9 @@ public class MBeanClientInterceptor
if (this == other) {
return true;
}
if (!(other instanceof MethodCacheKey)) {
if (!(other instanceof MethodCacheKey otherKey)) {
return false;
}
MethodCacheKey otherKey = (MethodCacheKey) other;
return (this.name.equals(otherKey.name) && Arrays.equals(this.parameterTypes, otherKey.parameterTypes));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 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.
@ -165,7 +165,7 @@ public class MBeanExporter extends MBeanRegistrationSupport implements MBeanExpo
private boolean exposeManagedResourceClassLoader = true;
/** A set of bean names that should be excluded from autodetection. */
private Set<String> excludedBeans = new HashSet<>();
private final Set<String> excludedBeans = new HashSet<>();
/** The MBeanExporterListeners registered with this exporter. */
@Nullable

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 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.
@ -73,19 +73,17 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef
}
private ModelMBeanNotificationInfo[] extractNotificationMetadata(Object mapValue) {
if (mapValue instanceof ManagedNotification) {
ManagedNotification mn = (ManagedNotification) mapValue;
if (mapValue instanceof ManagedNotification mn) {
return new ModelMBeanNotificationInfo[] {JmxMetadataUtils.convertToModelMBeanNotificationInfo(mn)};
}
else if (mapValue instanceof Collection) {
Collection<?> col = (Collection<?>) mapValue;
List<ModelMBeanNotificationInfo> result = new ArrayList<>();
for (Object colValue : col) {
if (!(colValue instanceof ManagedNotification)) {
if (!(colValue instanceof ManagedNotification mn)) {
throw new IllegalArgumentException(
"Property 'notificationInfoMappings' only accepts ManagedNotifications for Map values");
}
ManagedNotification mn = (ManagedNotification) colValue;
result.add(JmxMetadataUtils.convertToModelMBeanNotificationInfo(mn));
}
return result.toArray(new ModelMBeanNotificationInfo[0]);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 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.
@ -63,7 +63,7 @@ public class ConnectorServerFactoryBean extends MBeanRegistrationSupport
private String serviceUrl = DEFAULT_SERVICE_URL;
private Map<String, Object> environment = new HashMap<>();
private final Map<String, Object> environment = new HashMap<>();
@Nullable
private MBeanServerForwarder forwarder;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 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.
@ -58,7 +58,7 @@ public class MBeanServerConnectionFactoryBean
@Nullable
private JMXServiceURL serviceUrl;
private Map<String, Object> environment = new HashMap<>();
private final Map<String, Object> environment = new HashMap<>();
private boolean connectOnStartup = true;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2021 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.
@ -161,10 +161,9 @@ public class NotificationListenerHolder {
if (this == other) {
return true;
}
if (!(other instanceof NotificationListenerHolder)) {
if (!(other instanceof NotificationListenerHolder otherNlh)) {
return false;
}
NotificationListenerHolder otherNlh = (NotificationListenerHolder) other;
return (ObjectUtils.nullSafeEquals(this.notificationListener, otherNlh.notificationListener) &&
ObjectUtils.nullSafeEquals(this.notificationFilter, otherNlh.notificationFilter) &&
ObjectUtils.nullSafeEquals(this.handback, otherNlh.handback) &&

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 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.
@ -155,7 +155,7 @@ public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFac
@Override
public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType) {
return new ObjectProvider<T>() {
return new ObjectProvider<>() {
@Override
public T getObject() throws BeansException {
return getBean(requiredType);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 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.
@ -55,7 +55,7 @@ import org.springframework.util.function.SingletonSupplier;
@SuppressWarnings("serial")
public class AsyncAnnotationAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {
private Advice advice;
private final Advice advice;
private Pointcut pointcut;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 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.
@ -51,7 +51,7 @@ public class DefaultManagedAwareThreadFactory extends CustomizableThreadFactory
protected final Log logger = LogFactory.getLog(getClass());
private JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate();
private final JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate();
@Nullable
private String jndiName = "java:comp/DefaultManagedThreadFactory";

View File

@ -169,8 +169,7 @@ public class ThreadPoolTaskScheduler extends ExecutorConfigurationSupport
this.scheduledExecutor = createExecutor(this.poolSize, threadFactory, rejectedExecutionHandler);
if (this.scheduledExecutor instanceof ScheduledThreadPoolExecutor) {
ScheduledThreadPoolExecutor scheduledPoolExecutor = (ScheduledThreadPoolExecutor) this.scheduledExecutor;
if (this.scheduledExecutor instanceof ScheduledThreadPoolExecutor scheduledPoolExecutor) {
if (this.removeOnCancelPolicy) {
scheduledPoolExecutor.setRemoveOnCancelPolicy(true);
}

View File

@ -260,10 +260,9 @@ final class BitsCronField extends CronField {
if (this == o) {
return true;
}
if (!(o instanceof BitsCronField)) {
if (!(o instanceof BitsCronField other)) {
return false;
}
BitsCronField other = (BitsCronField) o;
return type() == other.type() && this.bits == other.bits;
}

View File

@ -81,10 +81,9 @@ final class CompositeCronField extends CronField {
if (this == o) {
return true;
}
if (!(o instanceof CompositeCronField)) {
if (!(o instanceof CompositeCronField other)) {
return false;
}
CompositeCronField other = (CompositeCronField) o;
return type() == other.type() &&
this.value.equals(other.value);
}

View File

@ -280,8 +280,7 @@ public final class CronExpression {
if (this == o) {
return true;
}
if (o instanceof CronExpression) {
CronExpression other = (CronExpression) o;
if (o instanceof CronExpression other) {
return Arrays.equals(this.fields, other.fields);
}
else {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 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.
@ -438,10 +438,9 @@ public class CronSequenceGenerator {
if (this == other) {
return true;
}
if (!(other instanceof CronSequenceGenerator)) {
if (!(other instanceof CronSequenceGenerator otherCron)) {
return false;
}
CronSequenceGenerator otherCron = (CronSequenceGenerator) other;
return (this.months.equals(otherCron.months) && this.daysOfMonth.equals(otherCron.daysOfMonth) &&
this.daysOfWeek.equals(otherCron.daysOfWeek) && this.hours.equals(otherCron.hours) &&
this.minutes.equals(otherCron.minutes) && this.seconds.equals(otherCron.seconds));

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@ -148,10 +148,9 @@ public class PeriodicTrigger implements Trigger {
if (this == other) {
return true;
}
if (!(other instanceof PeriodicTrigger)) {
if (!(other instanceof PeriodicTrigger otherTrigger)) {
return false;
}
PeriodicTrigger otherTrigger = (PeriodicTrigger) other;
return (this.fixedRate == otherTrigger.fixedRate && this.initialDelay == otherTrigger.initialDelay &&
this.period == otherTrigger.period);
}

View File

@ -360,10 +360,9 @@ final class QuartzCronField extends CronField {
if (this == o) {
return true;
}
if (!(o instanceof QuartzCronField)) {
if (!(o instanceof QuartzCronField other)) {
return false;
}
QuartzCronField other = (QuartzCronField) o;
return type() == other.type() &&
this.value.equals(other.value);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 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.
@ -241,11 +241,10 @@ public class StandardScriptFactory implements ScriptFactory, BeanClassLoaderAwar
if (adaptedIfc != null) {
ScriptEngine scriptEngine = this.scriptEngine;
if (!(scriptEngine instanceof Invocable)) {
if (!(scriptEngine instanceof Invocable invocable)) {
throw new ScriptCompilationException(scriptSource,
"ScriptEngine must implement Invocable in order to adapt it to an interface: " + scriptEngine);
}
Invocable invocable = (Invocable) scriptEngine;
if (script != null) {
script = invocable.getInterface(script, adaptedIfc);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2021 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.
@ -57,8 +57,7 @@ public abstract class UiApplicationContextUtils {
if (context.containsLocalBean(THEME_SOURCE_BEAN_NAME)) {
ThemeSource themeSource = context.getBean(THEME_SOURCE_BEAN_NAME, ThemeSource.class);
// Make ThemeSource aware of parent ThemeSource.
if (context.getParent() instanceof ThemeSource && themeSource instanceof HierarchicalThemeSource) {
HierarchicalThemeSource hts = (HierarchicalThemeSource) themeSource;
if (context.getParent() instanceof ThemeSource && themeSource instanceof HierarchicalThemeSource hts) {
if (hts.getParentThemeSource() == null) {
// Only set parent context as parent ThemeSource if no parent ThemeSource
// registered already.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 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.
@ -204,8 +204,7 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
public FieldError getFieldError(String field) {
String fixedField = fixedField(field);
for (ObjectError objectError : this.errors) {
if (objectError instanceof FieldError) {
FieldError fieldError = (FieldError) objectError;
if (objectError instanceof FieldError fieldError) {
if (isMatchingFieldError(fixedField, fieldError)) {
return fieldError;
}
@ -364,10 +363,9 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
if (this == other) {
return true;
}
if (!(other instanceof BindingResult)) {
if (!(other instanceof BindingResult otherResult)) {
return false;
}
BindingResult otherResult = (BindingResult) other;
return (getObjectName().equals(otherResult.getObjectName()) &&
ObjectUtils.nullSafeEquals(getTarget(), otherResult.getTarget()) &&
getAllErrors().equals(otherResult.getAllErrors()));

View File

@ -58,6 +58,7 @@ import org.springframework.validation.SmartValidator;
* Bean Validation 1.1 as well as 2.0.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.0
* @see SmartValidator
* @see CustomValidatorBean
@ -136,8 +137,8 @@ public class SpringValidatorAdapter implements SmartValidator, jakarta.validatio
private Class<?>[] asValidationGroups(Object... validationHints) {
Set<Class<?>> groups = new LinkedHashSet<>(4);
for (Object hint : validationHints) {
if (hint instanceof Class) {
groups.add((Class<?>) hint);
if (hint instanceof Class<?> clazz) {
groups.add(clazz);
}
}
return ClassUtils.toClassArray(groups);
@ -159,10 +160,9 @@ public class SpringValidatorAdapter implements SmartValidator, jakarta.validatio
ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
String errorCode = determineErrorCode(cd);
Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd);
if (errors instanceof BindingResult) {
if (errors instanceof BindingResult bindingResult) {
// Can do custom FieldError registration with invalid value from ConstraintViolation,
// as necessary for Hibernate Validator compatibility (non-indexed set path in field)
BindingResult bindingResult = (BindingResult) errors;
String nestedField = bindingResult.getNestedPath() + field;
if (nestedField.isEmpty()) {
String[] errorCodes = bindingResult.resolveMessageCodes(errorCode);
@ -269,8 +269,8 @@ public class SpringValidatorAdapter implements SmartValidator, jakarta.validatio
Map<String, Object> attributesToExpose = new TreeMap<>();
descriptor.getAttributes().forEach((attributeName, attributeValue) -> {
if (!internalAnnotationAttributes.contains(attributeName)) {
if (attributeValue instanceof String) {
attributeValue = new ResolvableAttribute(attributeValue.toString());
if (attributeValue instanceof String str) {
attributeValue = new ResolvableAttribute(str);
}
attributesToExpose.put(attributeName, attributeValue);
}

View File

@ -52,8 +52,7 @@ public class BindingAwareModelMap extends ExtendedModelMap {
}
private void removeBindingResultIfNecessary(Object key, @Nullable Object value) {
if (key instanceof String) {
String attributeName = (String) key;
if (key instanceof String attributeName) {
if (!attributeName.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + attributeName;
BindingResult bindingResult = (BindingResult) get(bindingResultKey);