From 67333a3f94b5ad3ab828988932f4a75759d0c53c Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 14 Oct 2021 17:09:30 +0200 Subject: [PATCH] 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`. --- .../AnnotationCacheOperationSource.java | 5 +-- .../cache/config/CacheAdviceParser.java | 12 ++--- .../cache/interceptor/CacheAspectSupport.java | 3 +- .../CacheOperationSourcePointcut.java | 5 +-- .../NameMatchCacheOperationSource.java | 7 ++- .../AnnotationBeanNameGenerator.java | 5 +-- .../AnnotationScopeMetadataResolver.java | 5 +-- .../CommonAnnotationBeanPostProcessor.java | 26 +++++------ ...onfigurationClassBeanDefinitionReader.java | 8 ++-- .../ConfigurationClassEnhancer.java | 6 +-- .../ConfigurationClassPostProcessor.java | 45 +++++++++---------- .../Jsr330ScopeMetadataResolver.java | 5 +-- .../AbstractApplicationEventMulticaster.java | 3 +- .../ApplicationListenerMethodAdapter.java | 3 +- .../expression/AnnotatedElementKey.java | 5 +-- .../expression/CachedExpressionEvaluator.java | 5 +-- .../support/AbstractApplicationContext.java | 5 +-- .../DefaultMessageSourceResolvable.java | 5 +-- .../PostProcessorRegistrationDelegate.java | 10 ++--- .../PropertySourcesPlaceholderConfigurer.java | 2 +- .../context/support/SimpleThreadScope.java | 4 +- .../standard/DateTimeFormatterFactory.java | 9 ++++ .../format/number/NumberStyleFormatter.java | 5 +-- .../support/FormattingConversionService.java | 5 +-- ...esourceOverridingShadowingClassLoader.java | 6 +-- .../jmx/access/MBeanClientInterceptor.java | 15 +++---- .../jmx/export/MBeanExporter.java | 4 +- ...bstractConfigurableMBeanInfoAssembler.java | 8 ++-- .../support/ConnectorServerFactoryBean.java | 4 +- .../MBeanServerConnectionFactoryBean.java | 4 +- .../support/NotificationListenerHolder.java | 5 +-- .../jndi/support/SimpleJndiBeanFactory.java | 4 +- .../annotation/AsyncAnnotationAdvisor.java | 4 +- .../DefaultManagedAwareThreadFactory.java | 4 +- .../concurrent/ThreadPoolTaskScheduler.java | 3 +- .../scheduling/support/BitsCronField.java | 3 +- .../support/CompositeCronField.java | 3 +- .../scheduling/support/CronExpression.java | 3 +- .../support/CronSequenceGenerator.java | 5 +-- .../scheduling/support/PeriodicTrigger.java | 5 +-- .../scheduling/support/QuartzCronField.java | 3 +- .../support/StandardScriptFactory.java | 5 +-- .../support/UiApplicationContextUtils.java | 5 +-- .../validation/AbstractBindingResult.java | 8 ++-- .../SpringValidatorAdapter.java | 12 ++--- .../support/BindingAwareModelMap.java | 3 +- 46 files changed, 137 insertions(+), 172 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java b/spring-context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java index 5d34d0e1031..230a36d1876 100644 --- a/spring-context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java +++ b/spring-context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java @@ -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); } diff --git a/spring-context/src/main/java/org/springframework/cache/config/CacheAdviceParser.java b/spring-context/src/main/java/org/springframework/cache/config/CacheAdviceParser.java index 2d75593e50d..c85dcad9065 100644 --- a/spring-context/src/main/java/org/springframework/cache/config/CacheAdviceParser.java +++ b/spring-context/src/main/java/org/springframework/cache/config/CacheAdviceParser.java @@ -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; diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java index c528a83206b..f29dfe3395f 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java @@ -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)); } diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperationSourcePointcut.java b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperationSourcePointcut.java index 5cf286faf63..d555d802a23 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperationSourcePointcut.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperationSourcePointcut.java @@ -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()); } diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/NameMatchCacheOperationSource.java b/spring-context/src/main/java/org/springframework/cache/interceptor/NameMatchCacheOperationSource.java index ac23ae7e9fd..d916e3f89c7 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/NameMatchCacheOperationSource.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/NameMatchCacheOperationSource.java @@ -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> nameMap = new LinkedHashMap<>(); + private final Map> 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); } diff --git a/spring-context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java b/spring-context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java index d686b5f2992..e690e76d86e 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java @@ -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 " + diff --git a/spring-context/src/main/java/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java b/spring-context/src/main/java/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java index fec4fb3e078..867d8d17e2b 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java @@ -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) { diff --git a/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java b/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java index c3efdfbed26..81b77e5e6a4 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java @@ -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 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; } diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java index 427e2bec83b..85b45e1574f 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java @@ -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); } diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java index 17079522c7f..eb53d63fbf8 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java @@ -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(); } }; diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java index 7913e61f56b..e5da4c44c79 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java @@ -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; diff --git a/spring-context/src/main/java/org/springframework/context/annotation/Jsr330ScopeMetadataResolver.java b/spring-context/src/main/java/org/springframework/context/annotation/Jsr330ScopeMetadataResolver.java index 7dc65574f4c..b3e1c6736ef 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/Jsr330ScopeMetadataResolver.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/Jsr330ScopeMetadataResolver.java @@ -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 annTypes = annDef.getMetadata().getAnnotationTypes(); String found = null; for (String annType : annTypes) { diff --git a/spring-context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java b/spring-context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java index d765539d0ad..26147f825ac 100644 --- a/spring-context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java +++ b/spring-context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java @@ -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)); } diff --git a/spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java b/spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java index bc7e1f93989..748fa55b393 100644 --- a/spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java +++ b/spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java @@ -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); } diff --git a/spring-context/src/main/java/org/springframework/context/expression/AnnotatedElementKey.java b/spring-context/src/main/java/org/springframework/context/expression/AnnotatedElementKey.java index 582e823ee0b..6476217f320 100644 --- a/spring-context/src/main/java/org/springframework/context/expression/AnnotatedElementKey.java +++ b/spring-context/src/main/java/org/springframework/context/expression/AnnotatedElementKey.java @@ -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 processedBeans = new HashSet<>(); - if (beanFactory instanceof BeanDefinitionRegistry) { - BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; + if (beanFactory instanceof BeanDefinitionRegistry registry) { List regularPostProcessors = new ArrayList<>(); List 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; } diff --git a/spring-context/src/main/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.java b/spring-context/src/main/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.java index a0907a1f3a1..c2d5e65d583 100644 --- a/spring-context/src/main/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.java +++ b/spring-context/src/main/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.java @@ -130,7 +130,7 @@ public class PropertySourcesPlaceholderConfigurer extends PlaceholderConfigurerS this.propertySources = new MutablePropertySources(); if (this.environment != null) { this.propertySources.addLast( - new PropertySource(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) { + new PropertySource<>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) { @Override @Nullable public String getProperty(String key) { diff --git a/spring-context/src/main/java/org/springframework/context/support/SimpleThreadScope.java b/spring-context/src/main/java/org/springframework/context/support/SimpleThreadScope.java index a1750518a42..0b237eb0b1c 100644 --- a/spring-context/src/main/java/org/springframework/context/support/SimpleThreadScope.java +++ b/spring-context/src/main/java/org/springframework/context/support/SimpleThreadScope.java @@ -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> threadScope = - new NamedThreadLocal>("SimpleThreadScope") { + new NamedThreadLocal<>("SimpleThreadScope") { @Override protected Map initialValue() { return new HashMap<>(); diff --git a/spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterFactory.java b/spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterFactory.java index c2fc3148dbc..df4f277e5de 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterFactory.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterFactory.java @@ -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; diff --git a/spring-context/src/main/java/org/springframework/format/number/NumberStyleFormatter.java b/spring-context/src/main/java/org/springframework/format/number/NumberStyleFormatter.java index 2ebbe36ce38..1597180306a 100644 --- a/spring-context/src/main/java/org/springframework/format/number/NumberStyleFormatter.java +++ b/spring-context/src/main/java/org/springframework/format/number/NumberStyleFormatter.java @@ -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); diff --git a/spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java b/spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java index 661c198fd49..9f502e1f9e4 100644 --- a/spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java +++ b/spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java @@ -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)); } diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/ResourceOverridingShadowingClassLoader.java b/spring-context/src/main/java/org/springframework/instrument/classloading/ResourceOverridingShadowingClassLoader.java index 4e68ab9fe52..21b75d9c2f2 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/ResourceOverridingShadowingClassLoader.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/ResourceOverridingShadowingClassLoader.java @@ -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 EMPTY_URL_ENUMERATION = new Enumeration() { + private static final Enumeration 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 overrides = new HashMap<>(); + private final Map overrides = new HashMap<>(); /** diff --git a/spring-context/src/main/java/org/springframework/jmx/access/MBeanClientInterceptor.java b/spring-context/src/main/java/org/springframework/jmx/access/MBeanClientInterceptor.java index 816459b3e54..e60e6bacd8b 100644 --- a/spring-context/src/main/java/org/springframework/jmx/access/MBeanClientInterceptor.java +++ b/spring-context/src/main/java/org/springframework/jmx/access/MBeanClientInterceptor.java @@ -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 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)); } diff --git a/spring-context/src/main/java/org/springframework/jmx/export/MBeanExporter.java b/spring-context/src/main/java/org/springframework/jmx/export/MBeanExporter.java index 98090fca6ce..fce9739404d 100644 --- a/spring-context/src/main/java/org/springframework/jmx/export/MBeanExporter.java +++ b/spring-context/src/main/java/org/springframework/jmx/export/MBeanExporter.java @@ -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 excludedBeans = new HashSet<>(); + private final Set excludedBeans = new HashSet<>(); /** The MBeanExporterListeners registered with this exporter. */ @Nullable diff --git a/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractConfigurableMBeanInfoAssembler.java b/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractConfigurableMBeanInfoAssembler.java index 4ebcbc4749d..525a2743265 100644 --- a/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractConfigurableMBeanInfoAssembler.java +++ b/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractConfigurableMBeanInfoAssembler.java @@ -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 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]); diff --git a/spring-context/src/main/java/org/springframework/jmx/support/ConnectorServerFactoryBean.java b/spring-context/src/main/java/org/springframework/jmx/support/ConnectorServerFactoryBean.java index c02f5fbca10..799c5c8cbb3 100644 --- a/spring-context/src/main/java/org/springframework/jmx/support/ConnectorServerFactoryBean.java +++ b/spring-context/src/main/java/org/springframework/jmx/support/ConnectorServerFactoryBean.java @@ -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 environment = new HashMap<>(); + private final Map environment = new HashMap<>(); @Nullable private MBeanServerForwarder forwarder; diff --git a/spring-context/src/main/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBean.java b/spring-context/src/main/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBean.java index 64258d71192..dfaf6d7afca 100644 --- a/spring-context/src/main/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBean.java +++ b/spring-context/src/main/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBean.java @@ -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 environment = new HashMap<>(); + private final Map environment = new HashMap<>(); private boolean connectOnStartup = true; diff --git a/spring-context/src/main/java/org/springframework/jmx/support/NotificationListenerHolder.java b/spring-context/src/main/java/org/springframework/jmx/support/NotificationListenerHolder.java index ac573bb1fa7..29df6edf539 100644 --- a/spring-context/src/main/java/org/springframework/jmx/support/NotificationListenerHolder.java +++ b/spring-context/src/main/java/org/springframework/jmx/support/NotificationListenerHolder.java @@ -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) && diff --git a/spring-context/src/main/java/org/springframework/jndi/support/SimpleJndiBeanFactory.java b/spring-context/src/main/java/org/springframework/jndi/support/SimpleJndiBeanFactory.java index 25249087720..186f546c611 100644 --- a/spring-context/src/main/java/org/springframework/jndi/support/SimpleJndiBeanFactory.java +++ b/spring-context/src/main/java/org/springframework/jndi/support/SimpleJndiBeanFactory.java @@ -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 ObjectProvider getBeanProvider(Class requiredType) { - return new ObjectProvider() { + return new ObjectProvider<>() { @Override public T getObject() throws BeansException { return getBean(requiredType); diff --git a/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.java b/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.java index 43326b42797..371c3433344 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.java +++ b/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.java @@ -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; diff --git a/spring-context/src/main/java/org/springframework/scheduling/concurrent/DefaultManagedAwareThreadFactory.java b/spring-context/src/main/java/org/springframework/scheduling/concurrent/DefaultManagedAwareThreadFactory.java index d52b92ed759..417a542c686 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/concurrent/DefaultManagedAwareThreadFactory.java +++ b/spring-context/src/main/java/org/springframework/scheduling/concurrent/DefaultManagedAwareThreadFactory.java @@ -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"; diff --git a/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler.java b/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler.java index 718c5833929..f1f0df51478 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler.java +++ b/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler.java @@ -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); } diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/BitsCronField.java b/spring-context/src/main/java/org/springframework/scheduling/support/BitsCronField.java index 8ea07d5ba85..9619c12ca5c 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/BitsCronField.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/BitsCronField.java @@ -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; } diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/CompositeCronField.java b/spring-context/src/main/java/org/springframework/scheduling/support/CompositeCronField.java index 97f808fc4c5..a3bf6eced06 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/CompositeCronField.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/CompositeCronField.java @@ -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); } diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java b/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java index e2e6687055e..93e65bf9c54 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java @@ -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 { diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java b/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java index 1f2b90f7cf1..e9c74387b2b 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java @@ -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)); diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/PeriodicTrigger.java b/spring-context/src/main/java/org/springframework/scheduling/support/PeriodicTrigger.java index 8e19a265f04..9292c008621 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/PeriodicTrigger.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/PeriodicTrigger.java @@ -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); } diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/QuartzCronField.java b/spring-context/src/main/java/org/springframework/scheduling/support/QuartzCronField.java index 0b72a273ab2..db1f20a7cb7 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/QuartzCronField.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/QuartzCronField.java @@ -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); } diff --git a/spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java b/spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java index 80a1a8fb6fa..3a14dcb33a5 100644 --- a/spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java +++ b/spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java @@ -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); } diff --git a/spring-context/src/main/java/org/springframework/ui/context/support/UiApplicationContextUtils.java b/spring-context/src/main/java/org/springframework/ui/context/support/UiApplicationContextUtils.java index bd842c419a7..675c705fb37 100644 --- a/spring-context/src/main/java/org/springframework/ui/context/support/UiApplicationContextUtils.java +++ b/spring-context/src/main/java/org/springframework/ui/context/support/UiApplicationContextUtils.java @@ -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. diff --git a/spring-context/src/main/java/org/springframework/validation/AbstractBindingResult.java b/spring-context/src/main/java/org/springframework/validation/AbstractBindingResult.java index b8857b15b50..2ef8f10ae0f 100644 --- a/spring-context/src/main/java/org/springframework/validation/AbstractBindingResult.java +++ b/spring-context/src/main/java/org/springframework/validation/AbstractBindingResult.java @@ -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())); diff --git a/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java b/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java index de02082dffe..ef6d19b3afb 100644 --- a/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java +++ b/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java @@ -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> 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 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); } diff --git a/spring-context/src/main/java/org/springframework/validation/support/BindingAwareModelMap.java b/spring-context/src/main/java/org/springframework/validation/support/BindingAwareModelMap.java index 9ac97145baf..c37eca8a7a0 100644 --- a/spring-context/src/main/java/org/springframework/validation/support/BindingAwareModelMap.java +++ b/spring-context/src/main/java/org/springframework/validation/support/BindingAwareModelMap.java @@ -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);