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"); * 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.
@ -168,10 +168,9 @@ public class AnnotationCacheOperationSource extends AbstractFallbackCacheOperati
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof AnnotationCacheOperationSource)) { if (!(other instanceof AnnotationCacheOperationSource otherCos)) {
return false; return false;
} }
AnnotationCacheOperationSource otherCos = (AnnotationCacheOperationSource) other;
return (this.annotationParsers.equals(otherCos.annotationParsers) && return (this.annotationParsers.equals(otherCos.annotationParsers) &&
this.publicMethodsOnly == otherCos.publicMethodsOnly); 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"); * 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.
@ -175,15 +175,15 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser {
*/ */
private static class Props { 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 @Nullable
private String[] caches; private String[] caches;

View File

@ -857,10 +857,9 @@ public abstract class CacheAspectSupport extends AbstractCacheInvoker
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof CacheOperationCacheKey)) { if (!(other instanceof CacheOperationCacheKey otherKey)) {
return false; return false;
} }
CacheOperationCacheKey otherKey = (CacheOperationCacheKey) other;
return (this.cacheOperation.equals(otherKey.cacheOperation) && return (this.cacheOperation.equals(otherKey.cacheOperation) &&
this.methodCacheKey.equals(otherKey.methodCacheKey)); 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"); * 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.
@ -53,10 +53,9 @@ abstract class CacheOperationSourcePointcut extends StaticMethodMatcherPointcut
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof CacheOperationSourcePointcut)) { if (!(other instanceof CacheOperationSourcePointcut otherPc)) {
return false; return false;
} }
CacheOperationSourcePointcut otherPc = (CacheOperationSourcePointcut) other;
return ObjectUtils.nullSafeEquals(getCacheOperationSource(), otherPc.getCacheOperationSource()); 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"); * 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.
@ -47,7 +47,7 @@ public class NameMatchCacheOperationSource implements CacheOperationSource, Seri
/** Keys are method names; values are TransactionAttributes. */ /** 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) { if (this == other) {
return true; return true;
} }
if (!(other instanceof NameMatchCacheOperationSource)) { if (!(other instanceof NameMatchCacheOperationSource otherTas)) {
return false; return false;
} }
NameMatchCacheOperationSource otherTas = (NameMatchCacheOperationSource) other;
return ObjectUtils.nullSafeEquals(this.nameMap, otherTas.nameMap); 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"); * 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.
@ -107,8 +107,7 @@ public class AnnotationBeanNameGenerator implements BeanNameGenerator {
}); });
if (isStereotypeWithNameValue(type, metaTypes, attributes)) { if (isStereotypeWithNameValue(type, metaTypes, attributes)) {
Object value = attributes.get("value"); Object value = attributes.get("value");
if (value instanceof String) { if (value instanceof String strVal) {
String strVal = (String) value;
if (StringUtils.hasLength(strVal)) { if (StringUtils.hasLength(strVal)) {
if (beanName != null && !strVal.equals(beanName)) { if (beanName != null && !strVal.equals(beanName)) {
throw new IllegalStateException("Stereotype annotations suggest inconsistent " + 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"); * 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.
@ -77,8 +77,7 @@ public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver {
@Override @Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) { public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
ScopeMetadata metadata = new ScopeMetadata(); ScopeMetadata metadata = new ScopeMetadata();
if (definition instanceof AnnotatedBeanDefinition) { if (definition instanceof AnnotatedBeanDefinition annDef) {
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor( AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(
annDef.getMetadata(), this.scopeAnnotationType); annDef.getMetadata(), this.scopeAnnotationType);
if (attributes != null) { if (attributes != null) {

View File

@ -266,8 +266,8 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
if (this.resourceFactory == null) { if (this.resourceFactory == null) {
this.resourceFactory = beanFactory; this.resourceFactory = beanFactory;
} }
if (beanFactory instanceof ConfigurableBeanFactory) { if (beanFactory instanceof ConfigurableBeanFactory configurableBeanFactory) {
this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory); this.embeddedValueResolver = new EmbeddedValueResolver(configurableBeanFactory);
} }
} }
@ -437,8 +437,8 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
if (element.lookupType.isInterface()) { if (element.lookupType.isInterface()) {
pf.addInterface(element.lookupType); pf.addInterface(element.lookupType);
} }
ClassLoader classLoader = (this.beanFactory instanceof ConfigurableBeanFactory ? ClassLoader classLoader = (this.beanFactory instanceof ConfigurableBeanFactory configurableBeanFactory ?
((ConfigurableBeanFactory) this.beanFactory).getBeanClassLoader() : null); configurableBeanFactory.getBeanClassLoader() : null);
return pf.getProxy(classLoader); return pf.getProxy(classLoader);
} }
@ -492,18 +492,17 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
Set<String> autowiredBeanNames; Set<String> autowiredBeanNames;
String name = element.name; String name = element.name;
if (factory instanceof AutowireCapableBeanFactory) { if (factory instanceof AutowireCapableBeanFactory autowireCapableBeanFactory) {
AutowireCapableBeanFactory beanFactory = (AutowireCapableBeanFactory) factory;
DependencyDescriptor descriptor = element.getDependencyDescriptor(); DependencyDescriptor descriptor = element.getDependencyDescriptor();
if (this.fallbackToDefaultTypeMatch && element.isDefaultName && !factory.containsBean(name)) { if (this.fallbackToDefaultTypeMatch && element.isDefaultName && !factory.containsBean(name)) {
autowiredBeanNames = new LinkedHashSet<>(); autowiredBeanNames = new LinkedHashSet<>();
resource = beanFactory.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, null); resource = autowireCapableBeanFactory.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, null);
if (resource == null) { if (resource == null) {
throw new NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object"); throw new NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object");
} }
} }
else { else {
resource = beanFactory.resolveBeanByName(name, descriptor); resource = autowireCapableBeanFactory.resolveBeanByName(name, descriptor);
autowiredBeanNames = Collections.singleton(name); autowiredBeanNames = Collections.singleton(name);
} }
} }
@ -512,11 +511,10 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
autowiredBeanNames = Collections.singleton(name); autowiredBeanNames = Collections.singleton(name);
} }
if (factory instanceof ConfigurableBeanFactory) { if (factory instanceof ConfigurableBeanFactory configurableBeanFactory) {
ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) factory;
for (String autowiredBeanName : autowiredBeanNames) { for (String autowiredBeanName : autowiredBeanNames) {
if (requestingBeanName != null && beanFactory.containsBean(autowiredBeanName)) { if (requestingBeanName != null && configurableBeanFactory.containsBean(autowiredBeanName)) {
beanFactory.registerDependentBean(autowiredBeanName, requestingBeanName); configurableBeanFactory.registerDependentBean(autowiredBeanName, requestingBeanName);
} }
} }
} }
@ -671,8 +669,8 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
if (beanFactory != null && beanFactory.containsBean(this.beanName)) { if (beanFactory != null && beanFactory.containsBean(this.beanName)) {
// Local match found for explicitly specified local bean name. // Local match found for explicitly specified local bean name.
Object bean = beanFactory.getBean(this.beanName, this.lookupType); Object bean = beanFactory.getBean(this.beanName, this.lookupType);
if (requestingBeanName != null && beanFactory instanceof ConfigurableBeanFactory) { if (requestingBeanName != null && beanFactory instanceof ConfigurableBeanFactory configurableBeanFactory) {
((ConfigurableBeanFactory) beanFactory).registerDependentBean(this.beanName, requestingBeanName); configurableBeanFactory.registerDependentBean(this.beanName, requestingBeanName);
} }
return bean; 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"); * 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.
@ -305,8 +305,7 @@ class ConfigurationClassBeanDefinitionReader {
// -> allow the current bean method to override, since both are at second-pass level. // -> 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, // However, if the bean method is an overloaded case on the same configuration class,
// preserve the existing bean definition. // preserve the existing bean definition.
if (existingBeanDef instanceof ConfigurationClassBeanDefinition) { if (existingBeanDef instanceof ConfigurationClassBeanDefinition ccbd) {
ConfigurationClassBeanDefinition ccbd = (ConfigurationClassBeanDefinition) existingBeanDef;
if (ccbd.getMetadata().getClassName().equals( if (ccbd.getMetadata().getClassName().equals(
beanMethod.getConfigurationClass().getMetadata().getClassName())) { beanMethod.getConfigurationClass().getMetadata().getClassName())) {
if (ccbd.getFactoryMethodMetadata().getMethodName().equals(ccbd.getFactoryMethodName())) { if (ccbd.getFactoryMethodMetadata().getMethodName().equals(ccbd.getFactoryMethodName())) {
@ -373,8 +372,7 @@ class ConfigurationClassBeanDefinitionReader {
// Instantiate the specified BeanDefinitionReader // Instantiate the specified BeanDefinitionReader
reader = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry); reader = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry);
// Delegate the current ResourceLoader to it if possible // Delegate the current ResourceLoader to it if possible
if (reader instanceof AbstractBeanDefinitionReader) { if (reader instanceof AbstractBeanDefinitionReader abdr) {
AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) reader);
abdr.setResourceLoader(this.resourceLoader); abdr.setResourceLoader(this.resourceLoader);
abdr.setEnvironment(this.environment); 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"); * 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.
@ -26,6 +26,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.aop.scope.ScopedProxyFactoryBean; import org.springframework.aop.scope.ScopedProxyFactoryBean;
import org.springframework.asm.Opcodes;
import org.springframework.asm.Type; import org.springframework.asm.Type;
import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware; 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.beans.factory.support.SimpleInstantiationStrategy;
import org.springframework.cglib.core.ClassGenerator; import org.springframework.cglib.core.ClassGenerator;
import org.springframework.cglib.core.ClassLoaderAwareGeneratorStrategy; import org.springframework.cglib.core.ClassLoaderAwareGeneratorStrategy;
import org.springframework.cglib.core.Constants;
import org.springframework.cglib.core.SpringNamingPolicy; import org.springframework.cglib.core.SpringNamingPolicy;
import org.springframework.cglib.proxy.Callback; import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.CallbackFilter; import org.springframework.cglib.proxy.CallbackFilter;
@ -219,7 +219,7 @@ class ConfigurationClassEnhancer {
ClassEmitterTransformer transformer = new ClassEmitterTransformer() { ClassEmitterTransformer transformer = new ClassEmitterTransformer() {
@Override @Override
public void end_class() { 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(); super.end_class();
} }
}; };

View File

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

View File

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

View File

@ -293,8 +293,7 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe
publishEvent(event); publishEvent(event);
} }
} }
else if (result instanceof Collection<?>) { else if (result instanceof Collection<?> events) {
Collection<?> events = (Collection<?>) result;
for (Object event : events) { for (Object event : events) {
publishEvent(event); 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"); * 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.
@ -55,10 +55,9 @@ public final class AnnotatedElementKey implements Comparable<AnnotatedElementKey
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof AnnotatedElementKey)) { if (!(other instanceof AnnotatedElementKey otherKey)) {
return false; return false;
} }
AnnotatedElementKey otherKey = (AnnotatedElementKey) other;
return (this.element.equals(otherKey.element) && return (this.element.equals(otherKey.element) &&
ObjectUtils.nullSafeEquals(this.targetClass, otherKey.targetClass)); 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"); * 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.
@ -118,10 +118,9 @@ public abstract class CachedExpressionEvaluator {
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof ExpressionKey)) { if (!(other instanceof ExpressionKey otherKey)) {
return false; return false;
} }
ExpressionKey otherKey = (ExpressionKey) other;
return (this.element.equals(otherKey.element) && return (this.element.equals(otherKey.element) &&
ObjectUtils.nullSafeEquals(this.expression, otherKey.expression)); ObjectUtils.nullSafeEquals(this.expression, otherKey.expression));
} }

View File

@ -211,7 +211,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
private Thread shutdownHook; private Thread shutdownHook;
/** ResourcePatternResolver used by this context. */ /** ResourcePatternResolver used by this context. */
private ResourcePatternResolver resourcePatternResolver; private final ResourcePatternResolver resourcePatternResolver;
/** LifecycleProcessor for managing the lifecycle of beans within this context. */ /** LifecycleProcessor for managing the lifecycle of beans within this context. */
@Nullable @Nullable
@ -771,8 +771,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource. // Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource hms) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) { if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource // Only set parent context as parent MessageSource if no parent MessageSource
// registered already. // 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"); * 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.
@ -174,10 +174,9 @@ public class DefaultMessageSourceResolvable implements MessageSourceResolvable,
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof MessageSourceResolvable)) { if (!(other instanceof MessageSourceResolvable otherResolvable)) {
return false; return false;
} }
MessageSourceResolvable otherResolvable = (MessageSourceResolvable) other;
return (ObjectUtils.nullSafeEquals(getCodes(), otherResolvable.getCodes()) && return (ObjectUtils.nullSafeEquals(getCodes(), otherResolvable.getCodes()) &&
ObjectUtils.nullSafeEquals(getArguments(), otherResolvable.getArguments()) && ObjectUtils.nullSafeEquals(getArguments(), otherResolvable.getArguments()) &&
ObjectUtils.nullSafeEquals(getDefaultMessage(), otherResolvable.getDefaultMessage())); 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.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.OrderComparator; import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered; import org.springframework.core.PriorityOrdered;
@ -75,15 +74,12 @@ final class PostProcessorRegistrationDelegate {
// Invoke BeanDefinitionRegistryPostProcessors first, if any. // Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>(); Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry) { if (beanFactory instanceof BeanDefinitionRegistry registry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>(); List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor registryProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry); registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor); registryProcessors.add(registryProcessor);
} }
@ -384,7 +380,7 @@ final class PostProcessorRegistrationDelegate {
private boolean isInfrastructureBean(@Nullable String beanName) { private boolean isInfrastructureBean(@Nullable String beanName) {
if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) { if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName); BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE); return (bd.getRole() == BeanDefinition.ROLE_INFRASTRUCTURE);
} }
return false; return false;
} }

View File

@ -130,7 +130,7 @@ public class PropertySourcesPlaceholderConfigurer extends PlaceholderConfigurerS
this.propertySources = new MutablePropertySources(); this.propertySources = new MutablePropertySources();
if (this.environment != null) { if (this.environment != null) {
this.propertySources.addLast( this.propertySources.addLast(
new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) { new PropertySource<>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
@Override @Override
@Nullable @Nullable
public String getProperty(String key) { 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"); * 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.
@ -56,7 +56,7 @@ public class SimpleThreadScope implements Scope {
private static final Log logger = LogFactory.getLog(SimpleThreadScope.class); private static final Log logger = LogFactory.getLog(SimpleThreadScope.class);
private final ThreadLocal<Map<String, Object>> threadScope = private final ThreadLocal<Map<String, Object>> threadScope =
new NamedThreadLocal<Map<String, Object>>("SimpleThreadScope") { new NamedThreadLocal<>("SimpleThreadScope") {
@Override @Override
protected Map<String, Object> initialValue() { protected Map<String, Object> initialValue() {
return new HashMap<>(); return new HashMap<>();

View File

@ -183,6 +183,15 @@ public class DateTimeFormatterFactory {
dateTimeFormatter = DateTimeFormatterUtils.createStrictDateTimeFormatter(this.pattern); dateTimeFormatter = DateTimeFormatterUtils.createStrictDateTimeFormatter(this.pattern);
} }
else if (this.iso != null && this.iso != ISO.NONE) { 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) { switch (this.iso) {
case DATE: case DATE:
dateTimeFormatter = DateTimeFormatter.ISO_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"); * 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.
@ -71,13 +71,12 @@ public class NumberStyleFormatter extends AbstractNumberFormatter {
@Override @Override
public NumberFormat getNumberFormat(Locale locale) { public NumberFormat getNumberFormat(Locale locale) {
NumberFormat format = NumberFormat.getInstance(locale); NumberFormat format = NumberFormat.getInstance(locale);
if (!(format instanceof DecimalFormat)) { if (!(format instanceof DecimalFormat decimalFormat)) {
if (this.pattern != null) { if (this.pattern != null) {
throw new IllegalStateException("Cannot support pattern for non-DecimalFormat: " + format); throw new IllegalStateException("Cannot support pattern for non-DecimalFormat: " + format);
} }
return format; return format;
} }
DecimalFormat decimalFormat = (DecimalFormat) format;
decimalFormat.setParseBigDecimal(true); decimalFormat.setParseBigDecimal(true);
if (this.pattern != null) { if (this.pattern != null) {
decimalFormat.applyPattern(this.pattern); 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"); * 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.
@ -370,10 +370,9 @@ public class FormattingConversionService extends GenericConversionService
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof AnnotationConverterKey)) { if (!(other instanceof AnnotationConverterKey otherKey)) {
return false; return false;
} }
AnnotationConverterKey otherKey = (AnnotationConverterKey) other;
return (this.fieldType == otherKey.fieldType && this.annotation.equals(otherKey.annotation)); 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"); * 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.
@ -36,7 +36,7 @@ import org.springframework.util.Assert;
*/ */
public class ResourceOverridingShadowingClassLoader extends ShadowingClassLoader { 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 @Override
public boolean hasMoreElements() { public boolean hasMoreElements() {
return false; return false;
@ -51,7 +51,7 @@ public class ResourceOverridingShadowingClassLoader extends ShadowingClassLoader
/** /**
* Key is asked for value: value is actual value. * 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"); * 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.
@ -566,8 +566,7 @@ public class MBeanClientInterceptor
Method fromMethod = targetClass.getMethod("from", CompositeData.class); Method fromMethod = targetClass.getMethod("from", CompositeData.class);
return ReflectionUtils.invokeMethod(fromMethod, null, result); return ReflectionUtils.invokeMethod(fromMethod, null, result);
} }
else if (result instanceof CompositeData[]) { else if (result instanceof CompositeData[] array) {
CompositeData[] array = (CompositeData[]) result;
if (targetClass.isArray()) { if (targetClass.isArray()) {
return convertDataArrayToTargetArray(array, targetClass); return convertDataArrayToTargetArray(array, targetClass);
} }
@ -583,8 +582,7 @@ public class MBeanClientInterceptor
Method fromMethod = targetClass.getMethod("from", TabularData.class); Method fromMethod = targetClass.getMethod("from", TabularData.class);
return ReflectionUtils.invokeMethod(fromMethod, null, result); return ReflectionUtils.invokeMethod(fromMethod, null, result);
} }
else if (result instanceof TabularData[]) { else if (result instanceof TabularData[] array) {
TabularData[] array = (TabularData[]) result;
if (targetClass.isArray()) { if (targetClass.isArray()) {
return convertDataArrayToTargetArray(array, targetClass); return convertDataArrayToTargetArray(array, targetClass);
} }
@ -621,8 +619,8 @@ public class MBeanClientInterceptor
Method fromMethod = elementType.getMethod("from", array.getClass().getComponentType()); Method fromMethod = elementType.getMethod("from", array.getClass().getComponentType());
Collection<Object> resultColl = CollectionFactory.createCollection(collectionType, Array.getLength(array)); Collection<Object> resultColl = CollectionFactory.createCollection(collectionType, Array.getLength(array));
for (int i = 0; i < array.length; i++) { for (Object element : array) {
resultColl.add(ReflectionUtils.invokeMethod(fromMethod, null, array[i])); resultColl.add(ReflectionUtils.invokeMethod(fromMethod, null, element));
} }
return resultColl; return resultColl;
} }
@ -660,10 +658,9 @@ public class MBeanClientInterceptor
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof MethodCacheKey)) { if (!(other instanceof MethodCacheKey otherKey)) {
return false; return false;
} }
MethodCacheKey otherKey = (MethodCacheKey) other;
return (this.name.equals(otherKey.name) && Arrays.equals(this.parameterTypes, otherKey.parameterTypes)); 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"); * 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.
@ -165,7 +165,7 @@ public class MBeanExporter extends MBeanRegistrationSupport implements MBeanExpo
private boolean exposeManagedResourceClassLoader = true; private boolean exposeManagedResourceClassLoader = true;
/** A set of bean names that should be excluded from autodetection. */ /** 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. */ /** The MBeanExporterListeners registered with this exporter. */
@Nullable @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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -73,19 +73,17 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef
} }
private ModelMBeanNotificationInfo[] extractNotificationMetadata(Object mapValue) { private ModelMBeanNotificationInfo[] extractNotificationMetadata(Object mapValue) {
if (mapValue instanceof ManagedNotification) { if (mapValue instanceof ManagedNotification mn) {
ManagedNotification mn = (ManagedNotification) mapValue;
return new ModelMBeanNotificationInfo[] {JmxMetadataUtils.convertToModelMBeanNotificationInfo(mn)}; return new ModelMBeanNotificationInfo[] {JmxMetadataUtils.convertToModelMBeanNotificationInfo(mn)};
} }
else if (mapValue instanceof Collection) { else if (mapValue instanceof Collection) {
Collection<?> col = (Collection<?>) mapValue; Collection<?> col = (Collection<?>) mapValue;
List<ModelMBeanNotificationInfo> result = new ArrayList<>(); List<ModelMBeanNotificationInfo> result = new ArrayList<>();
for (Object colValue : col) { for (Object colValue : col) {
if (!(colValue instanceof ManagedNotification)) { if (!(colValue instanceof ManagedNotification mn)) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Property 'notificationInfoMappings' only accepts ManagedNotifications for Map values"); "Property 'notificationInfoMappings' only accepts ManagedNotifications for Map values");
} }
ManagedNotification mn = (ManagedNotification) colValue;
result.add(JmxMetadataUtils.convertToModelMBeanNotificationInfo(mn)); result.add(JmxMetadataUtils.convertToModelMBeanNotificationInfo(mn));
} }
return result.toArray(new ModelMBeanNotificationInfo[0]); 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"); * 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.
@ -63,7 +63,7 @@ public class ConnectorServerFactoryBean extends MBeanRegistrationSupport
private String serviceUrl = DEFAULT_SERVICE_URL; private String serviceUrl = DEFAULT_SERVICE_URL;
private Map<String, Object> environment = new HashMap<>(); private final Map<String, Object> environment = new HashMap<>();
@Nullable @Nullable
private MBeanServerForwarder forwarder; 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"); * 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.
@ -58,7 +58,7 @@ public class MBeanServerConnectionFactoryBean
@Nullable @Nullable
private JMXServiceURL serviceUrl; private JMXServiceURL serviceUrl;
private Map<String, Object> environment = new HashMap<>(); private final Map<String, Object> environment = new HashMap<>();
private boolean connectOnStartup = true; 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"); * 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.
@ -161,10 +161,9 @@ public class NotificationListenerHolder {
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof NotificationListenerHolder)) { if (!(other instanceof NotificationListenerHolder otherNlh)) {
return false; return false;
} }
NotificationListenerHolder otherNlh = (NotificationListenerHolder) other;
return (ObjectUtils.nullSafeEquals(this.notificationListener, otherNlh.notificationListener) && return (ObjectUtils.nullSafeEquals(this.notificationListener, otherNlh.notificationListener) &&
ObjectUtils.nullSafeEquals(this.notificationFilter, otherNlh.notificationFilter) && ObjectUtils.nullSafeEquals(this.notificationFilter, otherNlh.notificationFilter) &&
ObjectUtils.nullSafeEquals(this.handback, otherNlh.handback) && 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"); * 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.
@ -155,7 +155,7 @@ public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFac
@Override @Override
public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType) { public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType) {
return new ObjectProvider<T>() { return new ObjectProvider<>() {
@Override @Override
public T getObject() throws BeansException { public T getObject() throws BeansException {
return getBean(requiredType); 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"); * 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.
@ -55,7 +55,7 @@ import org.springframework.util.function.SingletonSupplier;
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class AsyncAnnotationAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware { public class AsyncAnnotationAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {
private Advice advice; private final Advice advice;
private Pointcut pointcut; 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"); * 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.
@ -51,7 +51,7 @@ public class DefaultManagedAwareThreadFactory extends CustomizableThreadFactory
protected final Log logger = LogFactory.getLog(getClass()); protected final Log logger = LogFactory.getLog(getClass());
private JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate(); private final JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate();
@Nullable @Nullable
private String jndiName = "java:comp/DefaultManagedThreadFactory"; private String jndiName = "java:comp/DefaultManagedThreadFactory";

View File

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

View File

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

View File

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

View File

@ -280,8 +280,7 @@ public final class CronExpression {
if (this == o) { if (this == o) {
return true; return true;
} }
if (o instanceof CronExpression) { if (o instanceof CronExpression other) {
CronExpression other = (CronExpression) o;
return Arrays.equals(this.fields, other.fields); return Arrays.equals(this.fields, other.fields);
} }
else { 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"); * 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.
@ -438,10 +438,9 @@ public class CronSequenceGenerator {
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof CronSequenceGenerator)) { if (!(other instanceof CronSequenceGenerator otherCron)) {
return false; return false;
} }
CronSequenceGenerator otherCron = (CronSequenceGenerator) other;
return (this.months.equals(otherCron.months) && this.daysOfMonth.equals(otherCron.daysOfMonth) && return (this.months.equals(otherCron.months) && this.daysOfMonth.equals(otherCron.daysOfMonth) &&
this.daysOfWeek.equals(otherCron.daysOfWeek) && this.hours.equals(otherCron.hours) && this.daysOfWeek.equals(otherCron.daysOfWeek) && this.hours.equals(otherCron.hours) &&
this.minutes.equals(otherCron.minutes) && this.seconds.equals(otherCron.seconds)); 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"); * 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.
@ -148,10 +148,9 @@ public class PeriodicTrigger implements Trigger {
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof PeriodicTrigger)) { if (!(other instanceof PeriodicTrigger otherTrigger)) {
return false; return false;
} }
PeriodicTrigger otherTrigger = (PeriodicTrigger) other;
return (this.fixedRate == otherTrigger.fixedRate && this.initialDelay == otherTrigger.initialDelay && return (this.fixedRate == otherTrigger.fixedRate && this.initialDelay == otherTrigger.initialDelay &&
this.period == otherTrigger.period); this.period == otherTrigger.period);
} }

View File

@ -360,10 +360,9 @@ final class QuartzCronField extends CronField {
if (this == o) { if (this == o) {
return true; return true;
} }
if (!(o instanceof QuartzCronField)) { if (!(o instanceof QuartzCronField other)) {
return false; return false;
} }
QuartzCronField other = (QuartzCronField) o;
return type() == other.type() && return type() == other.type() &&
this.value.equals(other.value); 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"); * 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.
@ -241,11 +241,10 @@ public class StandardScriptFactory implements ScriptFactory, BeanClassLoaderAwar
if (adaptedIfc != null) { if (adaptedIfc != null) {
ScriptEngine scriptEngine = this.scriptEngine; ScriptEngine scriptEngine = this.scriptEngine;
if (!(scriptEngine instanceof Invocable)) { if (!(scriptEngine instanceof Invocable invocable)) {
throw new ScriptCompilationException(scriptSource, throw new ScriptCompilationException(scriptSource,
"ScriptEngine must implement Invocable in order to adapt it to an interface: " + scriptEngine); "ScriptEngine must implement Invocable in order to adapt it to an interface: " + scriptEngine);
} }
Invocable invocable = (Invocable) scriptEngine;
if (script != null) { if (script != null) {
script = invocable.getInterface(script, adaptedIfc); 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"); * 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.
@ -57,8 +57,7 @@ public abstract class UiApplicationContextUtils {
if (context.containsLocalBean(THEME_SOURCE_BEAN_NAME)) { if (context.containsLocalBean(THEME_SOURCE_BEAN_NAME)) {
ThemeSource themeSource = context.getBean(THEME_SOURCE_BEAN_NAME, ThemeSource.class); ThemeSource themeSource = context.getBean(THEME_SOURCE_BEAN_NAME, ThemeSource.class);
// Make ThemeSource aware of parent ThemeSource. // Make ThemeSource aware of parent ThemeSource.
if (context.getParent() instanceof ThemeSource && themeSource instanceof HierarchicalThemeSource) { if (context.getParent() instanceof ThemeSource && themeSource instanceof HierarchicalThemeSource hts) {
HierarchicalThemeSource hts = (HierarchicalThemeSource) themeSource;
if (hts.getParentThemeSource() == null) { if (hts.getParentThemeSource() == null) {
// Only set parent context as parent ThemeSource if no parent ThemeSource // Only set parent context as parent ThemeSource if no parent ThemeSource
// registered already. // 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"); * 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.
@ -204,8 +204,7 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
public FieldError getFieldError(String field) { public FieldError getFieldError(String field) {
String fixedField = fixedField(field); String fixedField = fixedField(field);
for (ObjectError objectError : this.errors) { for (ObjectError objectError : this.errors) {
if (objectError instanceof FieldError) { if (objectError instanceof FieldError fieldError) {
FieldError fieldError = (FieldError) objectError;
if (isMatchingFieldError(fixedField, fieldError)) { if (isMatchingFieldError(fixedField, fieldError)) {
return fieldError; return fieldError;
} }
@ -364,10 +363,9 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
if (this == other) { if (this == other) {
return true; return true;
} }
if (!(other instanceof BindingResult)) { if (!(other instanceof BindingResult otherResult)) {
return false; return false;
} }
BindingResult otherResult = (BindingResult) other;
return (getObjectName().equals(otherResult.getObjectName()) && return (getObjectName().equals(otherResult.getObjectName()) &&
ObjectUtils.nullSafeEquals(getTarget(), otherResult.getTarget()) && ObjectUtils.nullSafeEquals(getTarget(), otherResult.getTarget()) &&
getAllErrors().equals(otherResult.getAllErrors())); getAllErrors().equals(otherResult.getAllErrors()));

View File

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

View File

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