Apply "instanceof pattern matching" in spring-beans

This commit is contained in:
Sam Brannen 2023-01-27 17:53:53 +01:00
parent 556863d401
commit 8e2eeb5364
40 changed files with 157 additions and 169 deletions

View File

@ -100,8 +100,8 @@ class ExtendedBeanInfo implements BeanInfo {
this.delegate = delegate;
for (PropertyDescriptor pd : delegate.getPropertyDescriptors()) {
try {
this.propertyDescriptors.add(pd instanceof IndexedPropertyDescriptor ?
new SimpleIndexedPropertyDescriptor((IndexedPropertyDescriptor) pd) :
this.propertyDescriptors.add(pd instanceof IndexedPropertyDescriptor indexedPd ?
new SimpleIndexedPropertyDescriptor(indexedPd) :
new SimplePropertyDescriptor(pd));
}
catch (IntrospectionException ex) {
@ -170,8 +170,8 @@ class ExtendedBeanInfo implements BeanInfo {
this.propertyDescriptors.add(
new SimpleIndexedPropertyDescriptor(propertyName, null, null, null, method));
}
else if (existingPd instanceof IndexedPropertyDescriptor) {
((IndexedPropertyDescriptor) existingPd).setIndexedWriteMethod(method);
else if (existingPd instanceof IndexedPropertyDescriptor indexedPd) {
indexedPd.setIndexedWriteMethod(method);
}
else {
this.propertyDescriptors.remove(existingPd);
@ -189,8 +189,8 @@ class ExtendedBeanInfo implements BeanInfo {
for (PropertyDescriptor pd : this.propertyDescriptors) {
final Class<?> candidateType;
final String candidateName = pd.getName();
if (pd instanceof IndexedPropertyDescriptor ipd) {
candidateType = ipd.getIndexedPropertyType();
if (pd instanceof IndexedPropertyDescriptor indexedPd) {
candidateType = indexedPd.getIndexedPropertyType();
if (candidateName.equals(propertyName) &&
(candidateType.equals(propertyType) || candidateType.equals(propertyType.getComponentType()))) {
return pd;
@ -338,9 +338,9 @@ class ExtendedBeanInfo implements BeanInfo {
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof PropertyDescriptor &&
PropertyDescriptorUtils.equals(this, (PropertyDescriptor) other)));
public boolean equals(@Nullable Object obj) {
return (this == obj || (obj instanceof PropertyDescriptor that &&
PropertyDescriptorUtils.equals(this, that)));
}
@Override

View File

@ -366,9 +366,9 @@ public class MutablePropertyValues implements PropertyValues, Serializable {
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof MutablePropertyValues &&
this.propertyValueList.equals(((MutablePropertyValues) other).propertyValueList)));
public boolean equals(@Nullable Object obj) {
return (this == obj || (obj instanceof MutablePropertyValues that &&
this.propertyValueList.equals(that.propertyValueList)));
}
@Override

View File

@ -135,8 +135,8 @@ public class PropertyValue extends BeanMetadataAttributeAccessor implements Seri
public PropertyValue getOriginalPropertyValue() {
PropertyValue original = this;
Object source = getSource();
while (source instanceof PropertyValue && source != original) {
original = (PropertyValue) source;
while (source instanceof PropertyValue pv && source != original) {
original = pv;
source = original.getSource();
}
return original;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2023 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.
@ -140,12 +140,12 @@ class TypeConverterDelegate {
// Value not of required type?
if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
if (typeDescriptor != null && requiredType != null && Collection.class.isAssignableFrom(requiredType) &&
convertedValue instanceof String) {
convertedValue instanceof String text) {
TypeDescriptor elementTypeDesc = typeDescriptor.getElementTypeDescriptor();
if (elementTypeDesc != null) {
Class<?> elementType = elementTypeDesc.getType();
if (Class.class == elementType || Enum.class.isAssignableFrom(elementType)) {
convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
convertedValue = StringUtils.commaDelimitedListToStringArray(text);
}
}
}
@ -166,21 +166,19 @@ class TypeConverterDelegate {
}
else if (requiredType.isArray()) {
// Array required -> apply appropriate conversion of elements.
if (convertedValue instanceof String && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
if (convertedValue instanceof String text && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
convertedValue = StringUtils.commaDelimitedListToStringArray(text);
}
return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
}
else if (convertedValue instanceof Collection) {
else if (convertedValue instanceof Collection<?> coll) {
// Convert elements to target type, if determined.
convertedValue = convertToTypedCollection(
(Collection<?>) convertedValue, propertyName, requiredType, typeDescriptor);
convertedValue = convertToTypedCollection(coll, propertyName, requiredType, typeDescriptor);
standardConversion = true;
}
else if (convertedValue instanceof Map) {
else if (convertedValue instanceof Map<?, ?> map) {
// Convert keys and values to respective target type, if determined.
convertedValue = convertToTypedMap(
(Map<?, ?>) convertedValue, propertyName, requiredType, typeDescriptor);
convertedValue = convertToTypedMap(map, propertyName, requiredType, typeDescriptor);
standardConversion = true;
}
if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
@ -191,7 +189,7 @@ class TypeConverterDelegate {
// We can stringify any primitive value...
return (T) convertedValue.toString();
}
else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
else if (convertedValue instanceof String text && !requiredType.isInstance(convertedValue)) {
if (conversionAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
try {
Constructor<T> strCtor = requiredType.getConstructor(String.class);
@ -209,7 +207,7 @@ class TypeConverterDelegate {
}
}
}
String trimmedValue = ((String) convertedValue).trim();
String trimmedValue = text.trim();
if (requiredType.isEnum() && trimmedValue.isEmpty()) {
// It's an empty enum identifier: reset the enum value to null.
return null;
@ -217,9 +215,8 @@ class TypeConverterDelegate {
convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue);
standardConversion = true;
}
else if (convertedValue instanceof Number && Number.class.isAssignableFrom(requiredType)) {
convertedValue = NumberUtils.convertNumberToTargetClass(
(Number) convertedValue, (Class<Number>) requiredType);
else if (convertedValue instanceof Number num && Number.class.isAssignableFrom(requiredType)) {
convertedValue = NumberUtils.convertNumberToTargetClass(num, (Class<Number>) requiredType);
standardConversion = true;
}
}
@ -382,23 +379,22 @@ class TypeConverterDelegate {
Object returnValue = convertedValue;
if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) {
if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[] array) {
// Convert String array to a comma-separated String.
// Only applies if no PropertyEditor converted the String array before.
// The CSV String will be passed into a PropertyEditor's setAsText method, if any.
if (logger.isTraceEnabled()) {
logger.trace("Converting String array to comma-delimited String [" + convertedValue + "]");
}
convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue);
convertedValue = StringUtils.arrayToCommaDelimitedString(array);
}
if (convertedValue instanceof String) {
if (convertedValue instanceof String newTextValue) {
if (editor != null) {
// Use PropertyEditor's setAsText in case of a String value.
if (logger.isTraceEnabled()) {
logger.trace("Converting String to [" + requiredType + "] using property editor [" + editor + "]");
}
String newTextValue = (String) convertedValue;
return doConvertTextValue(oldValue, newTextValue, editor);
}
else if (String.class == requiredType) {
@ -431,9 +427,8 @@ class TypeConverterDelegate {
}
private Object convertToTypedArray(Object input, @Nullable String propertyName, Class<?> componentType) {
if (input instanceof Collection) {
if (input instanceof Collection<?> coll) {
// Convert Collection elements to array elements.
Collection<?> coll = (Collection<?>) input;
Object result = Array.newInstance(componentType, coll.size());
int i = 0;
for (Iterator<?> it = coll.iterator(); it.hasNext(); i++) {

View File

@ -204,8 +204,7 @@ public class BeanCreationException extends FatalBeanException {
}
if (this.relatedCauses != null) {
for (Throwable relatedCause : this.relatedCauses) {
if (relatedCause instanceof NestedRuntimeException &&
((NestedRuntimeException) relatedCause).contains(exClass)) {
if (relatedCause instanceof NestedRuntimeException nested && nested.contains(exClass)) {
return true;
}
}

View File

@ -266,11 +266,11 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
@Override
public void setBeanFactory(BeanFactory beanFactory) {
if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
if (!(beanFactory instanceof ConfigurableListableBeanFactory clbf)) {
throw new IllegalArgumentException(
"AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory: " + beanFactory);
}
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
this.beanFactory = clbf;
}

View File

@ -281,8 +281,8 @@ public class InjectionMetadata {
this.skip = true;
return true;
}
else if (pvs instanceof MutablePropertyValues) {
((MutablePropertyValues) pvs).registerProcessedProperty(this.pd.getName());
else if (pvs instanceof MutablePropertyValues mpvs) {
mpvs.registerProcessedProperty(this.pd.getName());
}
}
this.skip = false;
@ -299,8 +299,8 @@ public class InjectionMetadata {
return;
}
synchronized (pvs) {
if (Boolean.FALSE.equals(this.skip) && this.pd != null && pvs instanceof MutablePropertyValues) {
((MutablePropertyValues) pvs).clearProcessedProperty(this.pd.getName());
if (Boolean.FALSE.equals(this.skip) && this.pd != null && pvs instanceof MutablePropertyValues mpvs) {
mpvs.clearProcessedProperty(this.pd.getName());
}
}
}

View File

@ -279,7 +279,7 @@ public class QualifierAnnotationAutowireCandidateResolver extends GenericTypeAwa
actualValue = bd.getAttribute(attributeName);
}
if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
expectedValue instanceof String name && bdHolder.matchesName(name)) {
// Fall back on bean name (or alias) match
continue;
}

View File

@ -212,11 +212,11 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
}
private T invokeBeanSupplier(Executable executable, ThrowingSupplier<T> beanSupplier) {
if (!(executable instanceof Method)) {
if (!(executable instanceof Method method)) {
return beanSupplier.get();
}
try {
SimpleInstantiationStrategy.setCurrentlyInvokedFactoryMethod((Method) executable);
SimpleInstantiationStrategy.setCurrentlyInvokedFactoryMethod(method);
return beanSupplier.get();
}
finally {

View File

@ -124,8 +124,8 @@ public abstract class AbstractFactoryBean<T>
*/
protected TypeConverter getBeanTypeConverter() {
BeanFactory beanFactory = getBeanFactory();
if (beanFactory instanceof ConfigurableBeanFactory) {
return ((ConfigurableBeanFactory) beanFactory).getTypeConverter();
if (beanFactory instanceof ConfigurableBeanFactory cbf) {
return cbf.getTypeConverter();
}
else {
return new SimpleTypeConverter();

View File

@ -172,11 +172,11 @@ public class BeanDefinitionVisitor {
@SuppressWarnings("rawtypes")
@Nullable
protected Object resolveValue(@Nullable Object value) {
if (value instanceof BeanDefinition) {
visitBeanDefinition((BeanDefinition) value);
if (value instanceof BeanDefinition beanDef) {
visitBeanDefinition(beanDef);
}
else if (value instanceof BeanDefinitionHolder) {
visitBeanDefinition(((BeanDefinitionHolder) value).getBeanDefinition());
else if (value instanceof BeanDefinitionHolder beanDefHolder) {
visitBeanDefinition(beanDefHolder.getBeanDefinition());
}
else if (value instanceof RuntimeBeanReference ref) {
String newBeanName = resolveStringValue(ref.getBeanName());
@ -196,17 +196,17 @@ public class BeanDefinitionVisitor {
return new RuntimeBeanNameReference(newBeanName);
}
}
else if (value instanceof Object[]) {
visitArray((Object[]) value);
else if (value instanceof Object[] array) {
visitArray(array);
}
else if (value instanceof List) {
visitList((List) value);
else if (value instanceof List list) {
visitList(list);
}
else if (value instanceof Set) {
visitSet((Set) value);
else if (value instanceof Set set) {
visitSet(set);
}
else if (value instanceof Map) {
visitMap((Map) value);
else if (value instanceof Map map) {
visitMap(map);
}
else if (value instanceof TypedStringValue typedStringValue) {
String stringValue = typedStringValue.getValue();
@ -215,8 +215,8 @@ public class BeanDefinitionVisitor {
typedStringValue.setValue(visitedString);
}
}
else if (value instanceof String) {
return resolveStringValue((String) value);
else if (value instanceof String strValue) {
return resolveStringValue(strValue);
}
return value;
}

View File

@ -98,15 +98,15 @@ public class CustomScopeConfigurer implements BeanFactoryPostProcessor, BeanClas
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (this.scopes != null) {
this.scopes.forEach((scopeKey, value) -> {
if (value instanceof Scope) {
beanFactory.registerScope(scopeKey, (Scope) value);
if (value instanceof Scope scope) {
beanFactory.registerScope(scopeKey, scope);
}
else if (value instanceof Class<?> scopeClass) {
Assert.isAssignable(Scope.class, scopeClass, "Invalid scope class");
beanFactory.registerScope(scopeKey, (Scope) BeanUtils.instantiateClass(scopeClass));
}
else if (value instanceof String) {
Class<?> scopeClass = ClassUtils.resolveClassName((String) value, this.beanClassLoader);
else if (value instanceof String scopeClassName) {
Class<?> scopeClass = ClassUtils.resolveClassName(scopeClassName, this.beanClassLoader);
Assert.isAssignable(Scope.class, scopeClass, "Invalid scope class");
beanFactory.registerScope(scopeKey, (Scope) BeanUtils.instantiateClass(scopeClass));
}

View File

@ -86,8 +86,8 @@ public class MethodInvokingBean extends ArgumentConvertingMethodInvoker
@Override
public void setBeanFactory(BeanFactory beanFactory) {
if (beanFactory instanceof ConfigurableBeanFactory) {
this.beanFactory = (ConfigurableBeanFactory) beanFactory;
if (beanFactory instanceof ConfigurableBeanFactory cbf) {
this.beanFactory = cbf;
}
}
@ -123,11 +123,11 @@ public class MethodInvokingBean extends ArgumentConvertingMethodInvoker
return invoke();
}
catch (InvocationTargetException ex) {
if (ex.getTargetException() instanceof Exception) {
throw (Exception) ex.getTargetException();
if (ex.getTargetException() instanceof Exception exception) {
throw exception;
}
if (ex.getTargetException() instanceof Error) {
throw (Error) ex.getTargetException();
if (ex.getTargetException() instanceof Error error) {
throw error;
}
throw ex;
}

View File

@ -206,8 +206,8 @@ public class PropertyPathFactoryBean implements FactoryBean<Object>, BeanNameAwa
BeanWrapper target = this.targetBeanWrapper;
if (target != null) {
if (logger.isWarnEnabled() && this.targetBeanName != null &&
this.beanFactory instanceof ConfigurableBeanFactory &&
((ConfigurableBeanFactory) this.beanFactory).isCurrentlyInCreation(this.targetBeanName)) {
this.beanFactory instanceof ConfigurableBeanFactory cbf &&
cbf.isCurrentlyInCreation(this.targetBeanName)) {
logger.warn("Target bean '" + this.targetBeanName + "' is still in creation due to a circular " +
"reference - obtained value for property '" + this.propertyPath + "' may be outdated!");
}

View File

@ -250,11 +250,11 @@ public class ServiceLocatorFactoryBean implements FactoryBean<Object>, BeanFacto
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if (!(beanFactory instanceof ListableBeanFactory)) {
if (!(beanFactory instanceof ListableBeanFactory lbf)) {
throw new FatalBeanException(
"ServiceLocatorFactoryBean needs to run in a BeanFactory that is a ListableBeanFactory");
}
this.beanFactory = (ListableBeanFactory) beanFactory;
this.beanFactory = lbf;
}
@Override

View File

@ -129,10 +129,9 @@ public class YamlMapFactoryBean extends YamlProcessor implements FactoryBean<Map
private void merge(Map<String, Object> output, Map<String, Object> map) {
map.forEach((key, value) -> {
Object existing = output.get(key);
if (value instanceof Map && existing instanceof Map) {
// Inner cast required by Eclipse IDE.
Map<String, Object> result = new LinkedHashMap<>((Map<String, Object>) existing);
merge(result, (Map) value);
if (value instanceof Map valueMap && existing instanceof Map existingMap) {
Map<String, Object> result = new LinkedHashMap<>(existingMap);
merge(result, valueMap);
output.put(key, result);
}
else {

View File

@ -226,17 +226,16 @@ public abstract class YamlProcessor {
}
}
@SuppressWarnings("unchecked")
@SuppressWarnings({ "unchecked", "rawtypes" })
private Map<String, Object> asMap(Object object) {
// YAML can have numbers as keys
Map<String, Object> result = new LinkedHashMap<>();
if (!(object instanceof Map)) {
if (!(object instanceof Map map)) {
// A document can be a text literal
result.put("document", object);
return result;
}
Map<Object, Object> map = (Map<Object, Object>) object;
map.forEach((key, value) -> {
if (value instanceof Map) {
value = asMap(value);
@ -306,6 +305,7 @@ public abstract class YamlProcessor {
return result;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void buildFlattenedMap(Map<String, Object> result, Map<String, Object> source, @Nullable String path) {
source.forEach((key, value) -> {
if (StringUtils.hasText(path)) {
@ -319,16 +319,12 @@ public abstract class YamlProcessor {
if (value instanceof String) {
result.put(key, value);
}
else if (value instanceof Map) {
else if (value instanceof Map map) {
// Need a compound key
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) value;
buildFlattenedMap(result, map, key);
}
else if (value instanceof Collection) {
else if (value instanceof Collection collection) {
// Need a compound key
@SuppressWarnings("unchecked")
Collection<Object> collection = (Collection<Object>) value;
if (collection.isEmpty()) {
result.put(key, "");
}

View File

@ -318,8 +318,8 @@ public class GroovyBeanDefinitionReader extends AbstractBeanDefinitionReader imp
if (!ObjectUtils.isEmpty(args)) {
int index = args.length;
Object lastArg = args[index - 1];
if (lastArg instanceof Closure<?>) {
callable = (Closure<?>) lastArg;
if (lastArg instanceof Closure<?> closure) {
callable = closure;
index--;
}
constructorArgs = resolveConstructorArguments(args, 0, index);

View File

@ -139,22 +139,22 @@ class GroovyBeanDefinitionWrapper extends GroovyObjectSupport {
if (obj == null) {
throw new IllegalArgumentException("Parent bean cannot be set to a null runtime bean reference!");
}
if (obj instanceof String) {
this.parentName = (String) obj;
if (obj instanceof String name) {
this.parentName = name;
}
else if (obj instanceof RuntimeBeanReference) {
this.parentName = ((RuntimeBeanReference) obj).getBeanName();
else if (obj instanceof RuntimeBeanReference runtimeBeanReference) {
this.parentName = runtimeBeanReference.getBeanName();
}
else if (obj instanceof GroovyBeanDefinitionWrapper) {
this.parentName = ((GroovyBeanDefinitionWrapper) obj).getBeanName();
else if (obj instanceof GroovyBeanDefinitionWrapper wrapper) {
this.parentName = wrapper.getBeanName();
}
getBeanDefinition().setParentName(this.parentName);
getBeanDefinition().setAbstract(false);
}
public GroovyBeanDefinitionWrapper addProperty(String propertyName, Object propertyValue) {
if (propertyValue instanceof GroovyBeanDefinitionWrapper) {
propertyValue = ((GroovyBeanDefinitionWrapper) propertyValue).getBeanDefinition();
if (propertyValue instanceof GroovyBeanDefinitionWrapper wrapper) {
propertyValue = wrapper.getBeanDefinition();
}
getBeanDefinition().getPropertyValues().add(propertyName, propertyValue);
return this;

View File

@ -73,14 +73,14 @@ public class BeanComponentDefinition extends BeanDefinitionHolder implements Com
PropertyValues propertyValues = beanDefinitionHolder.getBeanDefinition().getPropertyValues();
for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
Object value = propertyValue.getValue();
if (value instanceof BeanDefinitionHolder) {
innerBeans.add(((BeanDefinitionHolder) value).getBeanDefinition());
if (value instanceof BeanDefinitionHolder beanDefHolder) {
innerBeans.add(beanDefHolder.getBeanDefinition());
}
else if (value instanceof BeanDefinition) {
innerBeans.add((BeanDefinition) value);
else if (value instanceof BeanDefinition beanDef) {
innerBeans.add(beanDef);
}
else if (value instanceof BeanReference) {
references.add((BeanReference) value);
else if (value instanceof BeanReference beanRef) {
references.add(beanRef);
}
}
this.innerBeanDefinitions = innerBeans.toArray(new BeanDefinition[0]);

View File

@ -1619,8 +1619,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
MutablePropertyValues mpvs = null;
List<PropertyValue> original;
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
if (pvs instanceof MutablePropertyValues _mpvs) {
mpvs = _mpvs;
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {

View File

@ -86,16 +86,16 @@ public abstract class AbstractBeanDefinitionReader implements BeanDefinitionRead
this.registry = registry;
// Determine ResourceLoader to use.
if (this.registry instanceof ResourceLoader) {
this.resourceLoader = (ResourceLoader) this.registry;
if (this.registry instanceof ResourceLoader _resourceLoader) {
this.resourceLoader = _resourceLoader;
}
else {
this.resourceLoader = new PathMatchingResourcePatternResolver();
}
// Inherit Environment if possible
if (this.registry instanceof EnvironmentCapable) {
this.environment = ((EnvironmentCapable) this.registry).getEnvironment();
if (this.registry instanceof EnvironmentCapable environmentCapable) {
this.environment = environmentCapable.getEnvironment();
}
else {
this.environment = new StandardEnvironment();
@ -213,10 +213,10 @@ public abstract class AbstractBeanDefinitionReader implements BeanDefinitionRead
"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
if (resourceLoader instanceof ResourcePatternResolver resourcePatternResolver) {
// Resource pattern matching available.
try {
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
Resource[] resources = resourcePatternResolver.getResources(location);
int count = loadBeanDefinitions(resources);
if (actualResources != null) {
Collections.addAll(actualResources, resources);

View File

@ -1540,8 +1540,8 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
if (evaluated instanceof Class<?> clazz) {
return clazz;
}
else if (evaluated instanceof String str) {
className = str;
else if (evaluated instanceof String name) {
className = name;
freshResolve = true;
}
else {

View File

@ -222,13 +222,13 @@ abstract class AutowireUtils {
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
for (Type typeArg : actualTypeArguments) {
if (typeArg.equals(genericReturnType)) {
if (arg instanceof Class) {
return (Class<?>) arg;
if (arg instanceof Class<?> clazz) {
return clazz;
}
else {
String className = null;
if (arg instanceof String) {
className = (String) arg;
if (arg instanceof String name) {
className = name;
}
else if (arg instanceof TypedStringValue typedValue) {
String targetTypeName = typedValue.getTargetTypeName();

View File

@ -81,9 +81,9 @@ class BeanDefinitionResource extends AbstractResource {
* This implementation compares the underlying BeanDefinition.
*/
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof BeanDefinitionResource &&
((BeanDefinitionResource) other).beanDefinition.equals(this.beanDefinition)));
public boolean equals(@Nullable Object obj) {
return (this == obj || (obj instanceof BeanDefinitionResource that &&
this.beanDefinition.equals(that.beanDefinition)));
}
/**

View File

@ -154,8 +154,8 @@ public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationSt
enhancer.setSuperclass(beanDefinition.getBeanClass());
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setAttemptLoad(true);
if (this.owner instanceof ConfigurableBeanFactory) {
ClassLoader cl = ((ConfigurableBeanFactory) this.owner).getBeanClassLoader();
if (this.owner instanceof ConfigurableBeanFactory cbf) {
ClassLoader cl = cbf.getBeanClassLoader();
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
}
enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));

View File

@ -766,8 +766,8 @@ class ConstructorResolver {
"] to required type [" + paramType.getName() + "]: " + ex.getMessage());
}
Object sourceHolder = valueHolder.getSource();
if (sourceHolder instanceof ConstructorArgumentValues.ValueHolder) {
Object sourceValue = ((ConstructorArgumentValues.ValueHolder) sourceHolder).getValue();
if (sourceHolder instanceof ConstructorArgumentValues.ValueHolder constructorValueHolder) {
Object sourceValue = constructorValueHolder.getValue();
args.resolveNecessary = true;
args.preparedArguments[paramIndex] = sourceValue;
}
@ -834,8 +834,8 @@ class ConstructorResolver {
else if (argValue instanceof BeanMetadataElement) {
argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
}
else if (argValue instanceof String) {
argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
else if (argValue instanceof String text) {
argValue = this.beanFactory.evaluateBeanDefinitionString(text, mbd);
}
Class<?> paramType = paramTypes[argIndex];
try {

View File

@ -188,11 +188,11 @@ public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanReg
* @throws BeansException if the given bean cannot be exposed as a FactoryBean
*/
protected FactoryBean<?> getFactoryBean(String beanName, Object beanInstance) throws BeansException {
if (!(beanInstance instanceof FactoryBean)) {
if (!(beanInstance instanceof FactoryBean<?> factoryBean)) {
throw new BeanCreationException(beanName,
"Bean instance of type [" + beanInstance.getClass() + "] is not a FactoryBean");
}
return (FactoryBean<?>) beanInstance;
return factoryBean;
}
/**

View File

@ -83,8 +83,8 @@ public class GenericTypeAwareAutowireCandidateResolver extends SimpleAutowireCan
ResolvableType targetType = null;
boolean cacheType = false;
RootBeanDefinition rbd = null;
if (bdHolder.getBeanDefinition() instanceof RootBeanDefinition) {
rbd = (RootBeanDefinition) bdHolder.getBeanDefinition();
if (bdHolder.getBeanDefinition() instanceof RootBeanDefinition rootBeanDef) {
rbd = rootBeanDef;
}
if (rbd != null) {
targetType = rbd.targetType;
@ -161,8 +161,8 @@ public class GenericTypeAwareAutowireCandidateResolver extends SimpleAutowireCan
if (decDef != null && this.beanFactory instanceof ConfigurableListableBeanFactory clbf) {
if (clbf.containsBeanDefinition(decDef.getBeanName())) {
BeanDefinition dbd = clbf.getMergedBeanDefinition(decDef.getBeanName());
if (dbd instanceof RootBeanDefinition) {
return (RootBeanDefinition) dbd;
if (dbd instanceof RootBeanDefinition rootBeanDef) {
return rootBeanDef;
}
}
}

View File

@ -75,11 +75,11 @@ public class ManagedProperties extends Properties implements Mergeable, BeanMeta
if (parent == null) {
return this;
}
if (!(parent instanceof Properties)) {
if (!(parent instanceof Properties properties)) {
throw new IllegalArgumentException("Cannot merge with object of type [" + parent.getClass() + "]");
}
Properties merged = new ManagedProperties();
merged.putAll((Properties) parent);
merged.putAll(properties);
merged.putAll(this);
return merged;
}

View File

@ -433,10 +433,10 @@ public class RootBeanDefinition extends AbstractBeanDefinition {
}
@Override
public void setInstanceSupplier(@Nullable Supplier<?> instanceSupplier) {
super.setInstanceSupplier(instanceSupplier);
Method factoryMethod = (instanceSupplier instanceof InstanceSupplier<?> ?
((InstanceSupplier<?>) instanceSupplier).getFactoryMethod() : null);
public void setInstanceSupplier(@Nullable Supplier<?> supplier) {
super.setInstanceSupplier(supplier);
Method factoryMethod = (supplier instanceof InstanceSupplier<?> instanceSupplier ?
instanceSupplier.getFactoryMethod() : null);
if (factoryMethod != null) {
setResolvedFactoryMethod(factoryMethod);
}

View File

@ -76,11 +76,11 @@ public class BeanConfigurerSupport implements BeanFactoryAware, InitializingBean
*/
@Override
public void setBeanFactory(BeanFactory beanFactory) {
if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
if (!(beanFactory instanceof ConfigurableListableBeanFactory clbf)) {
throw new IllegalArgumentException(
"Bean configurer aspect needs to run in a ConfigurableListableBeanFactory: " + beanFactory);
}
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
this.beanFactory = clbf;
if (this.beanWiringInfoResolver == null) {
this.beanWiringInfoResolver = createDefaultBeanWiringInfoResolver();
}
@ -158,8 +158,7 @@ public class BeanConfigurerSupport implements BeanFactoryAware, InitializingBean
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException) {
BeanCreationException bce = (BeanCreationException) rootCause;
if (rootCause instanceof BeanCurrentlyInCreationException bce) {
String bceBeanName = bce.getBeanName();
if (bceBeanName != null && beanFactory.isCurrentlyInCreation(bceBeanName)) {
if (logger.isDebugEnabled()) {

View File

@ -916,14 +916,14 @@ public class BeanDefinitionParserDelegate {
Element subElement = null;
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT) &&
if (node instanceof Element currentElement && !nodeNameEquals(node, DESCRIPTION_ELEMENT) &&
!nodeNameEquals(node, META_ELEMENT)) {
// Child element is what we're looking for.
if (subElement != null) {
error(elementName + " must not contain more than one sub-element", ele);
}
else {
subElement = (Element) node;
subElement = currentElement;
}
}
}
@ -1158,8 +1158,8 @@ public class BeanDefinitionParserDelegate {
for (int i = 0; i < elementNodes.getLength(); i++) {
Node node = elementNodes.item(i);
if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
target.add(parsePropertySubElement((Element) node, bd, defaultElementType));
if (node instanceof Element currentElement && !nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
target.add(parsePropertySubElement(currentElement, bd, defaultElementType));
}
}
}
@ -1309,13 +1309,13 @@ public class BeanDefinitionParserDelegate {
Element subElement = null;
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
if (node instanceof Element currentElement) {
// Child element is what we're looking for.
if (subElement != null) {
error("<key> element must not contain more than one value sub-element", keyEle);
}
else {
subElement = (Element) node;
subElement = currentElement;
}
}
}

View File

@ -120,8 +120,8 @@ public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver
if (handlerOrClassName == null) {
return null;
}
else if (handlerOrClassName instanceof NamespaceHandler) {
return (NamespaceHandler) handlerOrClassName;
else if (handlerOrClassName instanceof NamespaceHandler namespaceHandler) {
return namespaceHandler;
}
else {
String className = (String) handlerOrClassName;

View File

@ -52,8 +52,8 @@ public class XmlBeanDefinitionStoreException extends BeanDefinitionStoreExceptio
*/
public int getLineNumber() {
Throwable cause = getCause();
if (cause instanceof SAXParseException) {
return ((SAXParseException) cause).getLineNumber();
if (cause instanceof SAXParseException parseEx) {
return parseEx.getLineNumber();
}
return -1;
}

View File

@ -121,8 +121,8 @@ public class CustomNumberEditor extends PropertyEditorSupport {
*/
@Override
public void setValue(@Nullable Object value) {
if (value instanceof Number) {
super.setValue(NumberUtils.convertNumberToTargetClass((Number) value, this.numberClass));
if (value instanceof Number num) {
super.setValue(NumberUtils.convertNumberToTargetClass(num, this.numberClass));
}
else {
super.setValue(value);

View File

@ -68,9 +68,9 @@ public class PropertiesEditor extends PropertyEditorSupport {
*/
@Override
public void setValue(Object value) {
if (!(value instanceof Properties) && value instanceof Map) {
if (!(value instanceof Properties) && value instanceof Map<?, ?> map) {
Properties props = new Properties();
props.putAll((Map<?, ?>) value);
props.putAll(map);
super.setValue(props);
}
else {

View File

@ -98,11 +98,11 @@ public class ArgumentConvertingMethodInvoker extends MethodInvoker {
*/
public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) {
TypeConverter converter = getTypeConverter();
if (!(converter instanceof PropertyEditorRegistry)) {
if (!(converter instanceof PropertyEditorRegistry registry)) {
throw new IllegalStateException(
"TypeConverter does not implement PropertyEditorRegistry interface: " + converter);
}
((PropertyEditorRegistry) converter).registerCustomEditor(requiredType, propertyEditor);
registry.registerCustomEditor(requiredType, propertyEditor);
}

View File

@ -76,9 +76,9 @@ public class PropertyComparator<T> implements Comparator<T> {
public int compare(T o1, T o2) {
Object v1 = getPropertyValue(o1);
Object v2 = getPropertyValue(o2);
if (this.sortDefinition.isIgnoreCase() && (v1 instanceof String) && (v2 instanceof String)) {
v1 = ((String) v1).toLowerCase();
v2 = ((String) v2).toLowerCase();
if (this.sortDefinition.isIgnoreCase() && (v1 instanceof String text1) && (v2 instanceof String text2)) {
v1 = text1.toLowerCase();
v2 = text2.toLowerCase();
}
int result;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@ -116,9 +116,9 @@ public class ResourceEditorRegistrar implements PropertyEditorRegistrar {
doRegisterEditor(registry, Class.class, new ClassEditor(classLoader));
doRegisterEditor(registry, Class[].class, new ClassArrayEditor(classLoader));
if (this.resourceLoader instanceof ResourcePatternResolver) {
if (this.resourceLoader instanceof ResourcePatternResolver resourcePatternResolver) {
doRegisterEditor(registry, Resource[].class,
new ResourceArrayPropertyEditor((ResourcePatternResolver) this.resourceLoader, this.propertyResolver));
new ResourceArrayPropertyEditor(resourcePatternResolver, this.propertyResolver));
}
}
@ -127,8 +127,8 @@ public class ResourceEditorRegistrar implements PropertyEditorRegistrar {
* otherwise register as a custom editor.
*/
private void doRegisterEditor(PropertyEditorRegistry registry, Class<?> requiredType, PropertyEditor editor) {
if (registry instanceof PropertyEditorRegistrySupport) {
((PropertyEditorRegistrySupport) registry).overrideDefaultEditor(requiredType, editor);
if (registry instanceof PropertyEditorRegistrySupport registrySupport) {
registrySupport.overrideDefaultEditor(requiredType, editor);
}
else {
registry.registerCustomEditor(requiredType, editor);