Apply 'instanceof pattern matching' in spring-web

Closes gh-29530
This commit is contained in:
divcon
2022-11-21 00:36:07 +09:00
committed by Sam Brannen
parent 64c6a97130
commit 99ae209c25
50 changed files with 216 additions and 227 deletions

View File

@@ -202,8 +202,8 @@ public class HttpComponentsClientHttpRequestFactory implements ClientHttpRequest
if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) { if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
// Use request configuration given by the user, when available // Use request configuration given by the user, when available
RequestConfig config = null; RequestConfig config = null;
if (httpRequest instanceof Configurable) { if (httpRequest instanceof Configurable configurable) {
config = ((Configurable) httpRequest).getConfig(); config = configurable.getConfig();
} }
if (config == null) { if (config == null) {
config = createRequestConfig(client); config = createRequestConfig(client);
@@ -328,8 +328,8 @@ public class HttpComponentsClientHttpRequestFactory implements ClientHttpRequest
@Override @Override
public void destroy() throws Exception { public void destroy() throws Exception {
HttpClient httpClient = getHttpClient(); HttpClient httpClient = getHttpClient();
if (httpClient instanceof Closeable) { if (httpClient instanceof Closeable closeable) {
((Closeable) httpClient).close(); closeable.close();
} }
} }

View File

@@ -159,9 +159,8 @@ public class HttpComponentsClientHttpConnector implements ClientHttpConnector, C
@Override @Override
public void failed(Exception ex) { public void failed(Exception ex) {
Throwable t = ex; Throwable t = ex;
if (t instanceof HttpStreamResetException) { if (t instanceof HttpStreamResetException hsre) {
HttpStreamResetException httpStreamResetException = (HttpStreamResetException) ex; t = hsre.getCause();
t = httpStreamResetException.getCause();
} }
this.sink.error(t); this.sink.error(t);
} }

View File

@@ -131,16 +131,16 @@ public class JettyResourceFactory implements InitializingBean, DisposableBean {
} }
if (this.byteBufferPool == null) { if (this.byteBufferPool == null) {
this.byteBufferPool = new MappedByteBufferPool(2048, this.byteBufferPool = new MappedByteBufferPool(2048,
this.executor instanceof ThreadPool.SizedThreadPool this.executor instanceof ThreadPool.SizedThreadPool sizedThreadPool
? ((ThreadPool.SizedThreadPool) this.executor).getMaxThreads() / 2 ? sizedThreadPool.getMaxThreads() / 2
: ProcessorUtils.availableProcessors() * 2); : ProcessorUtils.availableProcessors() * 2);
} }
if (this.scheduler == null) { if (this.scheduler == null) {
this.scheduler = new ScheduledExecutorScheduler(name + "-scheduler", false); this.scheduler = new ScheduledExecutorScheduler(name + "-scheduler", false);
} }
if (this.executor instanceof LifeCycle) { if (this.executor instanceof LifeCycle lifeCycle) {
((LifeCycle)this.executor).start(); lifeCycle.start();
} }
this.scheduler.start(); this.scheduler.start();
} }
@@ -148,8 +148,8 @@ public class JettyResourceFactory implements InitializingBean, DisposableBean {
@Override @Override
public void destroy() throws Exception { public void destroy() throws Exception {
try { try {
if (this.executor instanceof LifeCycle) { if (this.executor instanceof LifeCycle lifeCycle) {
((LifeCycle)this.executor).stop(); lifeCycle.stop();
} }
} }
catch (Throwable ex) { catch (Throwable ex) {

View File

@@ -67,10 +67,10 @@ public class DecoderHttpMessageReader<T> implements HttpMessageReader<T> {
} }
private static void initLogger(Decoder<?> decoder) { private static void initLogger(Decoder<?> decoder) {
if (decoder instanceof AbstractDecoder && if (decoder instanceof AbstractDecoder<?> abstractDecoder &&
decoder.getClass().getName().startsWith("org.springframework.core.codec")) { decoder.getClass().getName().startsWith("org.springframework.core.codec")) {
Log logger = HttpLogging.forLog(((AbstractDecoder<?>) decoder).getLogger()); Log logger = HttpLogging.forLog(abstractDecoder.getLogger());
((AbstractDecoder<?>) decoder).setLogger(logger); abstractDecoder.setLogger(logger);
} }
} }
@@ -163,9 +163,8 @@ public class DecoderHttpMessageReader<T> implements HttpMessageReader<T> {
protected Map<String, Object> getReadHints(ResolvableType actualType, protected Map<String, Object> getReadHints(ResolvableType actualType,
ResolvableType elementType, ServerHttpRequest request, ServerHttpResponse response) { ResolvableType elementType, ServerHttpRequest request, ServerHttpResponse response) {
if (this.decoder instanceof HttpMessageDecoder) { if (this.decoder instanceof HttpMessageDecoder<?> httpMethodDecoder) {
HttpMessageDecoder<?> decoder = (HttpMessageDecoder<?>) this.decoder; return httpMethodDecoder.getDecodeHints(actualType, elementType, request, response);
return decoder.getDecodeHints(actualType, elementType, request, response);
} }
return Hints.none(); return Hints.none();
} }

View File

@@ -79,10 +79,10 @@ public class EncoderHttpMessageWriter<T> implements HttpMessageWriter<T> {
} }
private static void initLogger(Encoder<?> encoder) { private static void initLogger(Encoder<?> encoder) {
if (encoder instanceof AbstractEncoder && if (encoder instanceof AbstractEncoder<?> abstractEncoder &&
encoder.getClass().getName().startsWith("org.springframework.core.codec")) { encoder.getClass().getName().startsWith("org.springframework.core.codec")) {
Log logger = HttpLogging.forLog(((AbstractEncoder<?>) encoder).getLogger()); Log logger = HttpLogging.forLog(abstractEncoder.getLogger());
((AbstractEncoder<?>) encoder).setLogger(logger); abstractEncoder.setLogger(logger);
} }
} }
@@ -224,9 +224,8 @@ public class EncoderHttpMessageWriter<T> implements HttpMessageWriter<T> {
protected Map<String, Object> getWriteHints(ResolvableType streamType, ResolvableType elementType, protected Map<String, Object> getWriteHints(ResolvableType streamType, ResolvableType elementType,
@Nullable MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response) { @Nullable MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response) {
if (this.encoder instanceof HttpMessageEncoder) { if (this.encoder instanceof HttpMessageEncoder<?> httpMessageEncoder) {
HttpMessageEncoder<?> encoder = (HttpMessageEncoder<?>) this.encoder; return httpMessageEncoder.getEncodeHints(streamType, elementType, mediaType, request, response);
return encoder.getEncodeHints(streamType, elementType, mediaType, request, response);
} }
return Hints.none(); return Hints.none();
} }

View File

@@ -179,7 +179,7 @@ public class ResourceHttpMessageWriter implements HttpMessageWriter<Resource> {
private static Optional<Mono<Void>> zeroCopy(Resource resource, @Nullable ResourceRegion region, private static Optional<Mono<Void>> zeroCopy(Resource resource, @Nullable ResourceRegion region,
ReactiveHttpOutputMessage message, Map<String, Object> hints) { ReactiveHttpOutputMessage message, Map<String, Object> hints) {
if (message instanceof ZeroCopyHttpOutputMessage && resource.isFile()) { if (message instanceof ZeroCopyHttpOutputMessage zeroCopyHttpOutputMessage && resource.isFile()) {
try { try {
File file = resource.getFile(); File file = resource.getFile();
long pos = region != null ? region.getPosition() : 0; long pos = region != null ? region.getPosition() : 0;
@@ -188,7 +188,7 @@ public class ResourceHttpMessageWriter implements HttpMessageWriter<Resource> {
String formatted = region != null ? "region " + pos + "-" + (count) + " of " : ""; String formatted = region != null ? "region " + pos + "-" + (count) + " of " : "";
logger.debug(Hints.getLogPrefix(hints) + "Zero-copy " + formatted + "[" + resource + "]"); logger.debug(Hints.getLogPrefix(hints) + "Zero-copy " + formatted + "[" + resource + "]");
} }
return Optional.of(((ZeroCopyHttpOutputMessage) message).writeWith(file, pos, count)); return Optional.of(zeroCopyHttpOutputMessage.writeWith(file, pos, count));
} }
catch (IOException ex) { catch (IOException ex) {
// should not happen // should not happen

View File

@@ -121,8 +121,8 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
return Flux.from(input).map(element -> { return Flux.from(input).map(element -> {
ServerSentEvent<?> sse = (element instanceof ServerSentEvent ? ServerSentEvent<?> sse = (element instanceof ServerSentEvent<?> serverSentEvent ?
(ServerSentEvent<?>) element : ServerSentEvent.builder().data(element).build()); serverSentEvent : ServerSentEvent.builder().data(element).build());
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
String id = sse.id(); String id = sse.id();
@@ -150,9 +150,9 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
if (data == null) { if (data == null) {
result = Flux.just(encodeText(sb + "\n", mediaType, factory)); result = Flux.just(encodeText(sb + "\n", mediaType, factory));
} }
else if (data instanceof String) { else if (data instanceof String dataString) {
data = StringUtils.replace((String) data, "\n", "\ndata:"); dataString = StringUtils.replace(dataString, "\n", "\ndata:");
result = Flux.just(encodeText(sb + (String) data + "\n\n", mediaType, factory)); result = Flux.just(encodeText(sb + dataString + "\n\n", mediaType, factory));
} }
else { else {
result = encodeEvent(sb, data, dataType, mediaType, factory, hints); result = encodeEvent(sb, data, dataType, mediaType, factory, hints);
@@ -203,9 +203,8 @@ public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
private Map<String, Object> getEncodeHints(ResolvableType actualType, ResolvableType elementType, private Map<String, Object> getEncodeHints(ResolvableType actualType, ResolvableType elementType,
@Nullable MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response) { @Nullable MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response) {
if (this.encoder instanceof HttpMessageEncoder) { if (this.encoder instanceof HttpMessageEncoder<?> httpMessageEncoder) {
HttpMessageEncoder<?> encoder = (HttpMessageEncoder<?>) this.encoder; return httpMessageEncoder.getEncodeHints(actualType, elementType, mediaType, request, response);
return encoder.getEncodeHints(actualType, elementType, mediaType, request, response);
} }
return Hints.none(); return Hints.none();
} }

View File

@@ -264,12 +264,12 @@ public abstract class AbstractJackson2Decoder extends Jackson2CodecSupport imple
} }
private CodecException processException(IOException ex) { private CodecException processException(IOException ex) {
if (ex instanceof InvalidDefinitionException) { if (ex instanceof InvalidDefinitionException ide) {
JavaType type = ((InvalidDefinitionException) ex).getType(); JavaType type = ide.getType();
return new CodecException("Type definition error: " + type, ex); return new CodecException("Type definition error: " + type, ex);
} }
if (ex instanceof JsonProcessingException) { if (ex instanceof JsonProcessingException jpe) {
String originalMessage = ((JsonProcessingException) ex).getOriginalMessage(); String originalMessage = jpe.getOriginalMessage();
return new DecodingException("JSON decoding error: " + originalMessage, ex); return new DecodingException("JSON decoding error: " + originalMessage, ex);
} }
return new DecodingException("I/O error while parsing input stream", ex); return new DecodingException("I/O error while parsing input stream", ex);

View File

@@ -255,7 +255,7 @@ public abstract class Jackson2CodecSupport {
@Nullable @Nullable
protected MethodParameter getParameter(ResolvableType type) { protected MethodParameter getParameter(ResolvableType type) {
return (type.getSource() instanceof MethodParameter ? (MethodParameter) type.getSource() : null); return (type.getSource() instanceof MethodParameter methodParameter ? methodParameter : null);
} }
@Nullable @Nullable

View File

@@ -129,7 +129,7 @@ public class MultipartHttpMessageReader extends LoggingCodecSupport
} }
private List<Part> toList(Collection<Part> collection) { private List<Part> toList(Collection<Part> collection) {
return collection instanceof List ? (List<Part>) collection : new ArrayList<>(collection); return collection instanceof List<Part> partList ? partList : new ArrayList<>(collection);
} }
} }

View File

@@ -81,7 +81,7 @@ public class PartHttpMessageWriter extends MultipartWriterSupport implements Htt
String name = part.name(); String name = part.name();
if (!headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) { if (!headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
headers.setContentDispositionFormData(name, headers.setContentDispositionFormData(name,
(part instanceof FilePart ? ((FilePart) part).filename() : null)); (part instanceof FilePart filePart ? filePart.filename() : null));
} }
return Flux.concat( return Flux.concat(

View File

@@ -196,20 +196,18 @@ abstract class BaseCodecConfigurer implements CodecConfigurer {
private void addCodec(Object codec, boolean applyDefaultConfig) { private void addCodec(Object codec, boolean applyDefaultConfig) {
if (codec instanceof Decoder) { if (codec instanceof Decoder<?> decoder) {
codec = new DecoderHttpMessageReader<>((Decoder<?>) codec); codec = new DecoderHttpMessageReader<>(decoder);
} }
else if (codec instanceof Encoder) { else if (codec instanceof Encoder<?> encoder) {
codec = new EncoderHttpMessageWriter<>((Encoder<?>) codec); codec = new EncoderHttpMessageWriter<>(encoder);
} }
if (codec instanceof HttpMessageReader) { if (codec instanceof HttpMessageReader<?> reader) {
HttpMessageReader<?> reader = (HttpMessageReader<?>) codec;
boolean canReadToObject = reader.canRead(ResolvableType.forClass(Object.class), null); boolean canReadToObject = reader.canRead(ResolvableType.forClass(Object.class), null);
(canReadToObject ? this.objectReaders : this.typedReaders).put(reader, applyDefaultConfig); (canReadToObject ? this.objectReaders : this.typedReaders).put(reader, applyDefaultConfig);
} }
else if (codec instanceof HttpMessageWriter) { else if (codec instanceof HttpMessageWriter<?> writer) {
HttpMessageWriter<?> writer = (HttpMessageWriter<?>) codec;
boolean canWriteObject = writer.canWrite(ResolvableType.forClass(Object.class), null); boolean canWriteObject = writer.canWrite(ResolvableType.forClass(Object.class), null);
(canWriteObject ? this.objectWriters : this.typedWriters).put(writer, applyDefaultConfig); (canWriteObject ? this.objectWriters : this.typedWriters).put(writer, applyDefaultConfig);
} }

View File

@@ -424,13 +424,12 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
* if configured by the application, to the given codec , including any * if configured by the application, to the given codec , including any
* codec it contains. * codec it contains.
*/ */
@SuppressWarnings("rawtypes")
private void initCodec(@Nullable Object codec) { private void initCodec(@Nullable Object codec) {
if (codec instanceof DecoderHttpMessageReader) { if (codec instanceof DecoderHttpMessageReader<?> decoderHttpMessageReader) {
codec = ((DecoderHttpMessageReader) codec).getDecoder(); codec = decoderHttpMessageReader.getDecoder();
} }
else if (codec instanceof EncoderHttpMessageWriter) { else if (codec instanceof EncoderHttpMessageWriter<?> encoderHttpMessageWriter) {
codec = ((EncoderHttpMessageWriter<?>) codec).getEncoder(); codec = encoderHttpMessageWriter.getEncoder();
} }
if (codec == null) { if (codec == null) {
@@ -439,72 +438,72 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
Integer size = this.maxInMemorySize; Integer size = this.maxInMemorySize;
if (size != null) { if (size != null) {
if (codec instanceof AbstractDataBufferDecoder) { if (codec instanceof AbstractDataBufferDecoder<?> abstractDataBufferDecoder) {
((AbstractDataBufferDecoder<?>) codec).setMaxInMemorySize(size); abstractDataBufferDecoder.setMaxInMemorySize(size);
} }
if (protobufPresent) { if (protobufPresent) {
if (codec instanceof ProtobufDecoder) { if (codec instanceof ProtobufDecoder protobufDecoderCodec) {
((ProtobufDecoder) codec).setMaxMessageSize(size); protobufDecoderCodec.setMaxMessageSize(size);
} }
} }
if (kotlinSerializationCborPresent) { if (kotlinSerializationCborPresent) {
if (codec instanceof KotlinSerializationCborDecoder) { if (codec instanceof KotlinSerializationCborDecoder kotlinSerializationCborDecoderCodec) {
((KotlinSerializationCborDecoder) codec).setMaxInMemorySize(size); kotlinSerializationCborDecoderCodec.setMaxInMemorySize(size);
} }
} }
if (kotlinSerializationJsonPresent) { if (kotlinSerializationJsonPresent) {
if (codec instanceof KotlinSerializationJsonDecoder) { if (codec instanceof KotlinSerializationJsonDecoder kotlinSerializationJsonDecoderCodec) {
((KotlinSerializationJsonDecoder) codec).setMaxInMemorySize(size); kotlinSerializationJsonDecoderCodec.setMaxInMemorySize(size);
} }
} }
if (kotlinSerializationProtobufPresent) { if (kotlinSerializationProtobufPresent) {
if (codec instanceof KotlinSerializationProtobufDecoder) { if (codec instanceof KotlinSerializationProtobufDecoder kotlinSerializationProtobufDecoderCodec) {
((KotlinSerializationProtobufDecoder) codec).setMaxInMemorySize(size); kotlinSerializationProtobufDecoderCodec.setMaxInMemorySize(size);
} }
} }
if (jackson2Present) { if (jackson2Present) {
if (codec instanceof AbstractJackson2Decoder) { if (codec instanceof AbstractJackson2Decoder abstractJackson2Decoder) {
((AbstractJackson2Decoder) codec).setMaxInMemorySize(size); abstractJackson2Decoder.setMaxInMemorySize(size);
} }
} }
if (jaxb2Present) { if (jaxb2Present) {
if (codec instanceof Jaxb2XmlDecoder) { if (codec instanceof Jaxb2XmlDecoder jaxb2XmlDecoder) {
((Jaxb2XmlDecoder) codec).setMaxInMemorySize(size); jaxb2XmlDecoder.setMaxInMemorySize(size);
} }
} }
if (codec instanceof FormHttpMessageReader) { if (codec instanceof FormHttpMessageReader formHttpMessageReader) {
((FormHttpMessageReader) codec).setMaxInMemorySize(size); formHttpMessageReader.setMaxInMemorySize(size);
} }
if (codec instanceof ServerSentEventHttpMessageReader) { if (codec instanceof ServerSentEventHttpMessageReader serverSentEventHttpMessageReader) {
((ServerSentEventHttpMessageReader) codec).setMaxInMemorySize(size); serverSentEventHttpMessageReader.setMaxInMemorySize(size);
} }
if (codec instanceof DefaultPartHttpMessageReader) { if (codec instanceof DefaultPartHttpMessageReader defaultPartHttpMessageReader) {
((DefaultPartHttpMessageReader) codec).setMaxInMemorySize(size); defaultPartHttpMessageReader.setMaxInMemorySize(size);
} }
if (codec instanceof PartEventHttpMessageReader) { if (codec instanceof PartEventHttpMessageReader partEventHttpMessageReader) {
((PartEventHttpMessageReader) codec).setMaxInMemorySize(size); partEventHttpMessageReader.setMaxInMemorySize(size);
} }
} }
Boolean enable = this.enableLoggingRequestDetails; Boolean enable = this.enableLoggingRequestDetails;
if (enable != null) { if (enable != null) {
if (codec instanceof FormHttpMessageReader) { if (codec instanceof FormHttpMessageReader formHttpMessageReader) {
((FormHttpMessageReader) codec).setEnableLoggingRequestDetails(enable); formHttpMessageReader.setEnableLoggingRequestDetails(enable);
} }
if (codec instanceof MultipartHttpMessageReader) { if (codec instanceof MultipartHttpMessageReader multipartHttpMessageReader) {
((MultipartHttpMessageReader) codec).setEnableLoggingRequestDetails(enable); multipartHttpMessageReader.setEnableLoggingRequestDetails(enable);
} }
if (codec instanceof DefaultPartHttpMessageReader) { if (codec instanceof DefaultPartHttpMessageReader defaultPartHttpMessageReader) {
((DefaultPartHttpMessageReader) codec).setEnableLoggingRequestDetails(enable); defaultPartHttpMessageReader.setEnableLoggingRequestDetails(enable);
} }
if (codec instanceof PartEventHttpMessageReader) { if (codec instanceof PartEventHttpMessageReader partEventHttpMessageReader) {
((PartEventHttpMessageReader) codec).setEnableLoggingRequestDetails(enable); partEventHttpMessageReader.setEnableLoggingRequestDetails(enable);
} }
if (codec instanceof FormHttpMessageWriter) { if (codec instanceof FormHttpMessageWriter formHttpMessageWriter) {
((FormHttpMessageWriter) codec).setEnableLoggingRequestDetails(enable); formHttpMessageWriter.setEnableLoggingRequestDetails(enable);
} }
if (codec instanceof MultipartHttpMessageWriter) { if (codec instanceof MultipartHttpMessageWriter multipartHttpMessageWriter) {
((MultipartHttpMessageWriter) codec).setEnableLoggingRequestDetails(enable); multipartHttpMessageWriter.setEnableLoggingRequestDetails(enable);
} }
} }
@@ -513,17 +512,17 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
} }
// Recurse for nested codecs // Recurse for nested codecs
if (codec instanceof MultipartHttpMessageReader) { if (codec instanceof MultipartHttpMessageReader multipartHttpMessageReader) {
initCodec(((MultipartHttpMessageReader) codec).getPartReader()); initCodec(multipartHttpMessageReader.getPartReader());
} }
else if (codec instanceof MultipartHttpMessageWriter) { else if (codec instanceof MultipartHttpMessageWriter multipartHttpMessageWriter) {
initCodec(((MultipartHttpMessageWriter) codec).getFormWriter()); initCodec(multipartHttpMessageWriter.getFormWriter());
} }
else if (codec instanceof ServerSentEventHttpMessageReader) { else if (codec instanceof ServerSentEventHttpMessageReader serverSentEventHttpMessageReader) {
initCodec(((ServerSentEventHttpMessageReader) codec).getDecoder()); initCodec(serverSentEventHttpMessageReader.getDecoder());
} }
else if (codec instanceof ServerSentEventHttpMessageWriter) { else if (codec instanceof ServerSentEventHttpMessageWriter serverSentEventHttpMessageWriter) {
initCodec(((ServerSentEventHttpMessageWriter) codec).getEncoder()); initCodec(serverSentEventHttpMessageWriter.getEncoder());
} }
} }

View File

@@ -819,20 +819,20 @@ public class Jackson2ObjectMapperBuilder {
@SuppressWarnings("deprecation") // on Jackson 2.13: configure(MapperFeature, boolean) @SuppressWarnings("deprecation") // on Jackson 2.13: configure(MapperFeature, boolean)
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) { private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) {
if (feature instanceof JsonParser.Feature) { if (feature instanceof JsonParser.Feature jsonParserFeature) {
objectMapper.configure((JsonParser.Feature) feature, enabled); objectMapper.configure(jsonParserFeature, enabled);
} }
else if (feature instanceof JsonGenerator.Feature) { else if (feature instanceof JsonGenerator.Feature jsonGeneratorFeature) {
objectMapper.configure((JsonGenerator.Feature) feature, enabled); objectMapper.configure(jsonGeneratorFeature, enabled);
} }
else if (feature instanceof SerializationFeature) { else if (feature instanceof SerializationFeature serializationFeature) {
objectMapper.configure((SerializationFeature) feature, enabled); objectMapper.configure(serializationFeature, enabled);
} }
else if (feature instanceof DeserializationFeature) { else if (feature instanceof DeserializationFeature deserializationFeature) {
objectMapper.configure((DeserializationFeature) feature, enabled); objectMapper.configure(deserializationFeature, enabled);
} }
else if (feature instanceof MapperFeature) { else if (feature instanceof MapperFeature mapperFeature) {
objectMapper.configure((MapperFeature) feature, enabled); objectMapper.configure(mapperFeature, enabled);
} }
else { else {
throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName()); throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());

View File

@@ -69,8 +69,8 @@ public class MarshallingHttpMessageConverter extends AbstractXmlHttpMessageConve
public MarshallingHttpMessageConverter(Marshaller marshaller) { public MarshallingHttpMessageConverter(Marshaller marshaller) {
Assert.notNull(marshaller, "Marshaller must not be null"); Assert.notNull(marshaller, "Marshaller must not be null");
this.marshaller = marshaller; this.marshaller = marshaller;
if (marshaller instanceof Unmarshaller) { if (marshaller instanceof Unmarshaller um) {
this.unmarshaller = (Unmarshaller) marshaller; this.unmarshaller = um;
} }
} }

View File

@@ -335,8 +335,8 @@ public class ChannelSendOperator<T> extends Mono<Void> implements Scannable {
private void releaseCachedItem() { private void releaseCachedItem() {
synchronized (this) { synchronized (this) {
Object item = this.item; Object item = this.item;
if (item instanceof DataBuffer) { if (item instanceof DataBuffer dataBuffer) {
DataBufferUtils.release((DataBuffer) item); DataBufferUtils.release(dataBuffer);
} }
this.item = null; this.item = null;
} }

View File

@@ -100,8 +100,8 @@ final class DefaultSslInfo implements SslInfo {
List<X509Certificate> result = new ArrayList<>(certificates.length); List<X509Certificate> result = new ArrayList<>(certificates.length);
for (Certificate certificate : certificates) { for (Certificate certificate : certificates) {
if (certificate instanceof X509Certificate) { if (certificate instanceof X509Certificate x509Certificate) {
result.add((X509Certificate) certificate); result.add(x509Certificate);
} }
} }
return (!result.isEmpty() ? result.toArray(new X509Certificate[0]) : null); return (!result.isEmpty() ? result.toArray(new X509Certificate[0]) : null);

View File

@@ -105,7 +105,7 @@ class JettyHeadersAdapter implements MultiValueMap<String, String> {
@Override @Override
public boolean containsKey(Object key) { public boolean containsKey(Object key) {
return (key instanceof String && this.headers.contains((String) key)); return (key instanceof String headerName && this.headers.contains(headerName));
} }
@Override @Override
@@ -134,9 +134,9 @@ class JettyHeadersAdapter implements MultiValueMap<String, String> {
@Nullable @Nullable
@Override @Override
public List<String> remove(Object key) { public List<String> remove(Object key) {
if (key instanceof String) { if (key instanceof String headerName) {
List<String> oldValues = get(key); List<String> oldValues = get(key);
this.headers.remove((String) key); this.headers.remove(headerName);
return oldValues; return oldValues;
} }
return null; return null;

View File

@@ -196,8 +196,8 @@ class ReactorNetty2ServerHttpRequest extends AbstractServerHttpRequest {
@Override @Override
@Nullable @Nullable
protected String initId() { protected String initId() {
if (this.request instanceof Connection) { if (this.request instanceof Connection connection) {
return ((Connection) this.request).channel().id().asShortText() + return connection.channel().id().asShortText() +
"-" + logPrefixIndex.incrementAndGet(); "-" + logPrefixIndex.incrementAndGet();
} }
return null; return null;
@@ -212,8 +212,8 @@ class ReactorNetty2ServerHttpRequest extends AbstractServerHttpRequest {
if (id != null) { if (id != null) {
return id; return id;
} }
if (this.request instanceof Connection) { if (this.request instanceof Connection connection) {
return ((Connection) this.request).channel().id().asShortText() + return connection.channel().id().asShortText() +
"-" + logPrefixIndex.incrementAndGet(); "-" + logPrefixIndex.incrementAndGet();
} }
return getId(); return getId();

View File

@@ -193,8 +193,8 @@ class ReactorServerHttpRequest extends AbstractServerHttpRequest {
@Override @Override
@Nullable @Nullable
protected String initId() { protected String initId() {
if (this.request instanceof Connection) { if (this.request instanceof Connection connection) {
return ((Connection) this.request).channel().id().asShortText() + return connection.channel().id().asShortText() +
"-" + logPrefixIndex.incrementAndGet(); "-" + logPrefixIndex.incrementAndGet();
} }
return null; return null;
@@ -209,8 +209,8 @@ class ReactorServerHttpRequest extends AbstractServerHttpRequest {
if (id != null) { if (id != null) {
return id; return id;
} }
if (this.request instanceof Connection) { if (this.request instanceof Connection connection) {
return ((Connection) this.request).channel().id().asShortText() + return connection.channel().id().asShortText() +
"-" + logPrefixIndex.incrementAndGet(); "-" + logPrefixIndex.incrementAndGet();
} }
return getId(); return getId();

View File

@@ -123,11 +123,11 @@ public class ServerHttpRequestDecorator implements ServerHttpRequest {
* @since 5.3.3 * @since 5.3.3
*/ */
public static <T> T getNativeRequest(ServerHttpRequest request) { public static <T> T getNativeRequest(ServerHttpRequest request) {
if (request instanceof AbstractServerHttpRequest) { if (request instanceof AbstractServerHttpRequest abstractServerHttpRequest) {
return ((AbstractServerHttpRequest) request).getNativeRequest(); return abstractServerHttpRequest.getNativeRequest();
} }
else if (request instanceof ServerHttpRequestDecorator) { else if (request instanceof ServerHttpRequestDecorator serverHttpRequestDecorator) {
return getNativeRequest(((ServerHttpRequestDecorator) request).getDelegate()); return getNativeRequest(serverHttpRequestDecorator.getDelegate());
} }
else { else {
throw new IllegalArgumentException( throw new IllegalArgumentException(

View File

@@ -131,11 +131,11 @@ public class ServerHttpResponseDecorator implements ServerHttpResponse {
* @since 5.3.3 * @since 5.3.3
*/ */
public static <T> T getNativeResponse(ServerHttpResponse response) { public static <T> T getNativeResponse(ServerHttpResponse response) {
if (response instanceof AbstractServerHttpResponse) { if (response instanceof AbstractServerHttpResponse abstractServerHttpResponse) {
return ((AbstractServerHttpResponse) response).getNativeResponse(); return abstractServerHttpResponse.getNativeResponse();
} }
else if (response instanceof ServerHttpResponseDecorator) { else if (response instanceof ServerHttpResponseDecorator serverHttpResponseDecorator) {
return getNativeResponse(((ServerHttpResponseDecorator) response).getDelegate()); return getNativeResponse(serverHttpResponseDecorator.getDelegate());
} }
else { else {
throw new IllegalArgumentException( throw new IllegalArgumentException(

View File

@@ -74,8 +74,8 @@ public class ContentNegotiationManager implements ContentNegotiationStrategy, Me
Assert.notEmpty(strategies, "At least one ContentNegotiationStrategy is expected"); Assert.notEmpty(strategies, "At least one ContentNegotiationStrategy is expected");
this.strategies.addAll(strategies); this.strategies.addAll(strategies);
for (ContentNegotiationStrategy strategy : this.strategies) { for (ContentNegotiationStrategy strategy : this.strategies) {
if (strategy instanceof MediaTypeFileExtensionResolver) { if (strategy instanceof MediaTypeFileExtensionResolver mediaTypeFileExtensionResolver) {
this.resolvers.add((MediaTypeFileExtensionResolver) strategy); this.resolvers.add(mediaTypeFileExtensionResolver);
} }
} }
} }
@@ -180,8 +180,8 @@ public class ContentNegotiationManager implements ContentNegotiationStrategy, Me
public Map<String, MediaType> getMediaTypeMappings() { public Map<String, MediaType> getMediaTypeMappings() {
Map<String, MediaType> result = null; Map<String, MediaType> result = null;
for (MediaTypeFileExtensionResolver resolver : this.resolvers) { for (MediaTypeFileExtensionResolver resolver : this.resolvers) {
if (resolver instanceof MappingMediaTypeFileExtensionResolver) { if (resolver instanceof MappingMediaTypeFileExtensionResolver mappingMediaTypeFileExtensionResolver) {
Map<String, MediaType> map = ((MappingMediaTypeFileExtensionResolver) resolver).getMediaTypes(); Map<String, MediaType> map = mappingMediaTypeFileExtensionResolver.getMediaTypes();
if (CollectionUtils.isEmpty(map)) { if (CollectionUtils.isEmpty(map)) {
continue; continue;
} }

View File

@@ -122,7 +122,7 @@ public class WebExchangeDataBinder extends WebDataBinder {
protected static void addBindValue(Map<String, Object> params, String key, List<?> values) { protected static void addBindValue(Map<String, Object> params, String key, List<?> values) {
if (!CollectionUtils.isEmpty(values)) { if (!CollectionUtils.isEmpty(values)) {
values = values.stream() values = values.stream()
.map(value -> value instanceof FormFieldPart ? ((FormFieldPart) value).value() : value) .map(value -> value instanceof FormFieldPart formFieldPart ? formFieldPart.value() : value)
.toList(); .toList();
params.put(key, values.size() == 1 ? values.get(0) : values); params.put(key, values.size() == 1 ? values.get(0) : values);
} }

View File

@@ -94,9 +94,7 @@ public class HttpMessageConverterExtractor<T> implements ResponseExtractor<T> {
try { try {
for (HttpMessageConverter<?> messageConverter : this.messageConverters) { for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) { if (messageConverter instanceof GenericHttpMessageConverter genericMessageConverter) {
GenericHttpMessageConverter<?> genericMessageConverter =
(GenericHttpMessageConverter<?>) messageConverter;
if (genericMessageConverter.canRead(this.responseType, null, contentType)) { if (genericMessageConverter.canRead(this.responseType, null, contentType)) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
ResolvableType resolvableType = ResolvableType.forType(this.responseType); ResolvableType resolvableType = ResolvableType.forType(this.responseType);

View File

@@ -321,8 +321,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
* @since 4.3 * @since 4.3
*/ */
public void setDefaultUriVariables(Map<String, ?> uriVars) { public void setDefaultUriVariables(Map<String, ?> uriVars) {
if (this.uriTemplateHandler instanceof DefaultUriBuilderFactory) { if (this.uriTemplateHandler instanceof DefaultUriBuilderFactory defaultUriVariables) {
((DefaultUriBuilderFactory) this.uriTemplateHandler).setDefaultUriVariables(uriVars); defaultUriVariables.setDefaultUriVariables(uriVars);
} }
else { else {
throw new IllegalArgumentException( throw new IllegalArgumentException(
@@ -723,8 +723,7 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
} }
private URI resolveUrl(RequestEntity<?> entity) { private URI resolveUrl(RequestEntity<?> entity) {
if (entity instanceof RequestEntity.UriTemplateRequestEntity) { if (entity instanceof RequestEntity.UriTemplateRequestEntity<?> ext) {
RequestEntity.UriTemplateRequestEntity<?> ext = (RequestEntity.UriTemplateRequestEntity<?>) entity;
if (ext.getVars() != null) { if (ext.getVars() != null) {
return this.uriTemplateHandler.expand(ext.getUriTemplate(), ext.getVars()); return this.uriTemplateHandler.expand(ext.getUriTemplate(), ext.getVars());
} }
@@ -1003,19 +1002,18 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
} }
private boolean canReadResponse(Type responseType, HttpMessageConverter<?> converter) { private boolean canReadResponse(Type responseType, HttpMessageConverter<?> converter) {
Class<?> responseClass = (responseType instanceof Class ? (Class<?>) responseType : null); Class<?> responseClass = (responseType instanceof Class<?> type ? type : null);
if (responseClass != null) { if (responseClass != null) {
return converter.canRead(responseClass, null); return converter.canRead(responseClass, null);
} }
else if (converter instanceof GenericHttpMessageConverter) { else if (converter instanceof GenericHttpMessageConverter<?> genericConverter) {
GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
return genericConverter.canRead(responseType, null, null); return genericConverter.canRead(responseType, null, null);
} }
return false; return false;
} }
private Stream<MediaType> getSupportedMediaTypes(Type type, HttpMessageConverter<?> converter) { private Stream<MediaType> getSupportedMediaTypes(Type type, HttpMessageConverter<?> converter) {
Type rawType = (type instanceof ParameterizedType ? ((ParameterizedType) type).getRawType() : type); Type rawType = (type instanceof ParameterizedType parameterizedType ? parameterizedType.getRawType() : type);
Class<?> clazz = (rawType instanceof Class ? (Class<?>) rawType : null); Class<?> clazz = (rawType instanceof Class ? (Class<?>) rawType : null);
return (clazz != null ? converter.getSupportedMediaTypes(clazz) : converter.getSupportedMediaTypes()) return (clazz != null ? converter.getSupportedMediaTypes(clazz) : converter.getSupportedMediaTypes())
.stream() .stream()
@@ -1042,8 +1040,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
public HttpEntityRequestCallback(@Nullable Object requestBody, @Nullable Type responseType) { public HttpEntityRequestCallback(@Nullable Object requestBody, @Nullable Type responseType) {
super(responseType); super(responseType);
if (requestBody instanceof HttpEntity) { if (requestBody instanceof HttpEntity<?> httpEntity) {
this.requestEntity = (HttpEntity<?>) requestBody; this.requestEntity = httpEntity;
} }
else if (requestBody != null) { else if (requestBody != null) {
this.requestEntity = new HttpEntity<>(requestBody); this.requestEntity = new HttpEntity<>(requestBody);
@@ -1070,8 +1068,8 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
} }
else { else {
Class<?> requestBodyClass = requestBody.getClass(); Class<?> requestBodyClass = requestBody.getClass();
Type requestBodyType = (this.requestEntity instanceof RequestEntity ? Type requestBodyType = (this.requestEntity instanceof RequestEntity<?> re ?
((RequestEntity<?>)this.requestEntity).getType() : requestBodyClass); re.getType() : requestBodyClass);
HttpHeaders httpHeaders = httpRequest.getHeaders(); HttpHeaders httpHeaders = httpRequest.getHeaders();
HttpHeaders requestHeaders = this.requestEntity.getHeaders(); HttpHeaders requestHeaders = this.requestEntity.getHeaders();
MediaType requestContentType = requestHeaders.getContentType(); MediaType requestContentType = requestHeaders.getContentType();

View File

@@ -65,9 +65,9 @@ public class ContextCleanupListener implements ServletContextListener {
String attrName = attrNames.nextElement(); String attrName = attrNames.nextElement();
if (attrName.startsWith("org.springframework.")) { if (attrName.startsWith("org.springframework.")) {
Object attrValue = servletContext.getAttribute(attrName); Object attrValue = servletContext.getAttribute(attrName);
if (attrValue instanceof DisposableBean) { if (attrValue instanceof DisposableBean disposableBean) {
try { try {
((DisposableBean) attrValue).destroy(); disposableBean.destroy();
} }
catch (Throwable ex) { catch (Throwable ex) {
if (logger.isWarnEnabled()) { if (logger.isWarnEnabled()) {

View File

@@ -51,11 +51,10 @@ public class RequestContextListener implements ServletRequestListener {
@Override @Override
public void requestInitialized(ServletRequestEvent requestEvent) { public void requestInitialized(ServletRequestEvent requestEvent) {
if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) { if (!(requestEvent.getServletRequest() instanceof HttpServletRequest request)) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Request is not an HttpServletRequest: " + requestEvent.getServletRequest()); "Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
} }
HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
ServletRequestAttributes attributes = new ServletRequestAttributes(request); ServletRequestAttributes attributes = new ServletRequestAttributes(request);
request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes); request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
LocaleContextHolder.setLocale(request.getLocale()); LocaleContextHolder.setLocale(request.getLocale());

View File

@@ -209,8 +209,8 @@ public abstract class AbstractRefreshableWebApplicationContext extends AbstractR
@Override @Override
protected void initPropertySources() { protected void initPropertySources() {
ConfigurableEnvironment env = getEnvironment(); ConfigurableEnvironment env = getEnvironment();
if (env instanceof ConfigurableWebEnvironment) { if (env instanceof ConfigurableWebEnvironment configurableWebEnv) {
((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, this.servletConfig); configurableWebEnv.initPropertySources(this.servletContext, this.servletConfig);
} }
} }

View File

@@ -208,8 +208,8 @@ public class GenericWebApplicationContext extends GenericApplicationContext
@Override @Override
protected void initPropertySources() { protected void initPropertySources() {
ConfigurableEnvironment env = getEnvironment(); ConfigurableEnvironment env = getEnvironment();
if (env instanceof ConfigurableWebEnvironment) { if (env instanceof ConfigurableWebEnvironment configurableWebEnv) {
((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, null); configurableWebEnv.initPropertySources(this.servletContext, null);
} }
} }

View File

@@ -104,11 +104,11 @@ public class ServletContextAwareProcessor implements BeanPostProcessor {
@Override @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (getServletContext() != null && bean instanceof ServletContextAware) { if (getServletContext() != null && bean instanceof ServletContextAware servletContextAware) {
((ServletContextAware) bean).setServletContext(getServletContext()); servletContextAware.setServletContext(getServletContext());
} }
if (getServletConfig() != null && bean instanceof ServletConfigAware) { if (getServletConfig() != null && bean instanceof ServletConfigAware servletConfigAware) {
((ServletConfigAware) bean).setServletConfig(getServletConfig()); servletConfigAware.setServletConfig(getServletConfig());
} }
return bean; return bean;
} }

View File

@@ -114,19 +114,19 @@ public abstract class WebApplicationContextUtils {
if (attr == null) { if (attr == null) {
return null; return null;
} }
if (attr instanceof RuntimeException) { if (attr instanceof RuntimeException re) {
throw (RuntimeException) attr; throw re;
} }
if (attr instanceof Error) { if (attr instanceof Error error) {
throw (Error) attr; throw error;
} }
if (attr instanceof Exception) { if (attr instanceof Exception ex) {
throw new IllegalStateException((Exception) attr); throw new IllegalStateException(ex);
} }
if (!(attr instanceof WebApplicationContext)) { if (!(attr instanceof WebApplicationContext wac)) {
throw new IllegalStateException("Context attribute is not of type WebApplicationContext: " + attr); throw new IllegalStateException("Context attribute is not of type WebApplicationContext: " + attr);
} }
return (WebApplicationContext) attr; return wac;
} }
/** /**
@@ -311,10 +311,10 @@ public abstract class WebApplicationContextUtils {
*/ */
private static ServletRequestAttributes currentRequestAttributes() { private static ServletRequestAttributes currentRequestAttributes() {
RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes(); RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes();
if (!(requestAttr instanceof ServletRequestAttributes)) { if (!(requestAttr instanceof ServletRequestAttributes servletRequestAttributes)) {
throw new IllegalStateException("Current request is not a servlet request"); throw new IllegalStateException("Current request is not a servlet request");
} }
return (ServletRequestAttributes) requestAttr; return servletRequestAttributes;
} }

View File

@@ -76,8 +76,8 @@ public abstract class WebApplicationObjectSupport extends ApplicationObjectSuppo
@Override @Override
protected void initApplicationContext(ApplicationContext context) { protected void initApplicationContext(ApplicationContext context) {
super.initApplicationContext(context); super.initApplicationContext(context);
if (this.servletContext == null && context instanceof WebApplicationContext) { if (this.servletContext == null && context instanceof WebApplicationContext wac) {
this.servletContext = ((WebApplicationContext) context).getServletContext(); this.servletContext = wac.getServletContext();
if (this.servletContext != null) { if (this.servletContext != null) {
initServletContext(this.servletContext); initServletContext(this.servletContext);
} }
@@ -108,8 +108,8 @@ public abstract class WebApplicationObjectSupport extends ApplicationObjectSuppo
@Nullable @Nullable
protected final WebApplicationContext getWebApplicationContext() throws IllegalStateException { protected final WebApplicationContext getWebApplicationContext() throws IllegalStateException {
ApplicationContext ctx = getApplicationContext(); ApplicationContext ctx = getApplicationContext();
if (ctx instanceof WebApplicationContext) { if (ctx instanceof WebApplicationContext wac) {
return (WebApplicationContext) getApplicationContext(); return wac;
} }
else if (isContextRequired()) { else if (isContextRequired()) {
throw new IllegalStateException("WebApplicationObjectSupport instance [" + this + throw new IllegalStateException("WebApplicationObjectSupport instance [" + this +

View File

@@ -110,8 +110,8 @@ public class DelegatingNavigationHandlerProxy extends NavigationHandler {
@Override @Override
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) { public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
NavigationHandler handler = getDelegate(facesContext); NavigationHandler handler = getDelegate(facesContext);
if (handler instanceof DecoratingNavigationHandler) { if (handler instanceof DecoratingNavigationHandler decoratingNavigationHandler) {
((DecoratingNavigationHandler) handler).handleNavigation( decoratingNavigationHandler.handleNavigation(
facesContext, fromAction, outcome, this.originalNavigationHandler); facesContext, fromAction, outcome, this.originalNavigationHandler);
} }
else { else {

View File

@@ -55,16 +55,16 @@ public abstract class FacesContextUtils {
if (attr == null) { if (attr == null) {
return null; return null;
} }
if (attr instanceof RuntimeException) { if (attr instanceof RuntimeException re) {
throw (RuntimeException) attr; throw re;
} }
if (attr instanceof Error) { if (attr instanceof Error error) {
throw (Error) attr; throw error;
} }
if (!(attr instanceof WebApplicationContext)) { if (!(attr instanceof WebApplicationContext wac)) {
throw new IllegalStateException("Root context attribute is not of type WebApplicationContext: " + attr); throw new IllegalStateException("Root context attribute is not of type WebApplicationContext: " + attr);
} }
return (WebApplicationContext) attr; return wac;
} }
/** /**

View File

@@ -160,8 +160,8 @@ public class ControllerAdviceBean implements Ordered {
if (this.order == null) { if (this.order == null) {
String beanName = null; String beanName = null;
Object resolvedBean = null; Object resolvedBean = null;
if (this.beanFactory != null && this.beanOrName instanceof String) { if (this.beanFactory != null && this.beanOrName instanceof String stringBeanName) {
beanName = (String) this.beanOrName; beanName = stringBeanName;
String targetBeanName = ScopedProxyUtils.getTargetBeanName(beanName); String targetBeanName = ScopedProxyUtils.getTargetBeanName(beanName);
boolean isScopedProxy = this.beanFactory.containsBean(targetBeanName); boolean isScopedProxy = this.beanFactory.containsBean(targetBeanName);
// Avoid eager @ControllerAdvice bean resolution for scoped proxies, // Avoid eager @ControllerAdvice bean resolution for scoped proxies,

View File

@@ -65,8 +65,8 @@ public class MapMethodProcessor implements HandlerMethodArgumentResolver, Handle
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
if (returnValue instanceof Map){ if (returnValue instanceof Map returnValueMap) {
mavContainer.addAllAttributes((Map) returnValue); mavContainer.addAllAttributes(returnValueMap);
} }
else if (returnValue != null) { else if (returnValue != null) {
// should not happen // should not happen

View File

@@ -406,9 +406,9 @@ public class ModelAttributeMethodProcessor implements HandlerMethodArgumentResol
Object[] validationHints = ValidationAnnotationUtils.determineValidationHints(ann); Object[] validationHints = ValidationAnnotationUtils.determineValidationHints(ann);
if (validationHints != null) { if (validationHints != null) {
for (Validator validator : binder.getValidators()) { for (Validator validator : binder.getValidators()) {
if (validator instanceof SmartValidator) { if (validator instanceof SmartValidator smartValidator) {
try { try {
((SmartValidator) validator).validateValue(targetType, fieldName, value, smartValidator.validateValue(targetType, fieldName, value,
binder.getBindingResult(), validationHints); binder.getBindingResult(), validationHints);
} }
catch (IllegalArgumentException ex) { catch (IllegalArgumentException ex) {

View File

@@ -65,8 +65,8 @@ public class ModelMethodProcessor implements HandlerMethodArgumentResolver, Hand
if (returnValue == null) { if (returnValue == null) {
return; return;
} }
else if (returnValue instanceof Model) { else if (returnValue instanceof Model model) {
mavContainer.addAllAttributes(((Model) returnValue).asMap()); mavContainer.addAllAttributes(model.asMap());
} }
else { else {
// should not happen // should not happen

View File

@@ -234,8 +234,8 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod
Assert.state(name != null, "Unresolvable parameter name"); Assert.state(name != null, "Unresolvable parameter name");
parameter = parameter.nestedIfOptional(); parameter = parameter.nestedIfOptional();
if (value instanceof Optional) { if (value instanceof Optional<?> optionalValue) {
value = ((Optional<?>) value).orElse(null); value = optionalValue.orElse(null);
} }
if (value == null) { if (value == null) {
@@ -245,8 +245,8 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod
} }
builder.queryParam(name); builder.queryParam(name);
} }
else if (value instanceof Collection) { else if (value instanceof Collection<?> collectionValue) {
for (Object element : (Collection<?>) value) { for (Object element : collectionValue) {
element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element); element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element);
builder.queryParam(name, element); builder.queryParam(name, element);
} }
@@ -263,8 +263,8 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod
if (value == null) { if (value == null) {
return null; return null;
} }
else if (value instanceof String) { else if (value instanceof String stringValue) {
return (String) value; return stringValue;
} }
else if (cs != null) { else if (cs != null) {
return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR); return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR);

View File

@@ -94,8 +94,8 @@ public class HandlerMethodReturnValueHandlerComposite implements HandlerMethodRe
private boolean isAsyncReturnValue(@Nullable Object value, MethodParameter returnType) { private boolean isAsyncReturnValue(@Nullable Object value, MethodParameter returnType) {
for (HandlerMethodReturnValueHandler handler : this.returnValueHandlers) { for (HandlerMethodReturnValueHandler handler : this.returnValueHandlers) {
if (handler instanceof AsyncHandlerMethodReturnValueHandler && if (handler instanceof AsyncHandlerMethodReturnValueHandler asyncHandlerMethodReturnValueHandler &&
((AsyncHandlerMethodReturnValueHandler) handler).isAsyncReturnValue(value, returnType)) { asyncHandlerMethodReturnValueHandler.isAsyncReturnValue(value, returnType)) {
return true; return true;
} }
} }

View File

@@ -215,14 +215,14 @@ public class InvocableHandlerMethod extends HandlerMethod {
catch (InvocationTargetException ex) { catch (InvocationTargetException ex) {
// Unwrap for HandlerExceptionResolvers ... // Unwrap for HandlerExceptionResolvers ...
Throwable targetException = ex.getTargetException(); Throwable targetException = ex.getTargetException();
if (targetException instanceof RuntimeException) { if (targetException instanceof RuntimeException re) {
throw (RuntimeException) targetException; throw re;
} }
else if (targetException instanceof Error) { else if (targetException instanceof Error error) {
throw (Error) targetException; throw error;
} }
else if (targetException instanceof Exception) { else if (targetException instanceof Exception exception) {
throw (Exception) targetException; throw exception;
} }
else { else {
throw new IllegalStateException(formatInvokeError("Invocation failure", args), targetException); throw new IllegalStateException(formatInvokeError("Invocation failure", args), targetException);

View File

@@ -106,7 +106,7 @@ public class ModelAndViewContainer {
*/ */
@Nullable @Nullable
public String getViewName() { public String getViewName() {
return (this.view instanceof String ? (String) this.view : null); return (this.view instanceof String stringView ? stringView : null);
} }
/** /**

View File

@@ -89,8 +89,8 @@ class MultipartFileResource extends AbstractResource {
@Override @Override
public boolean equals(@Nullable Object other) { public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof MultipartFileResource && return (this == other || (other instanceof MultipartFileResource multipartFileResource &&
((MultipartFileResource) other).multipartFile.equals(this.multipartFile))); multipartFileResource.multipartFile.equals(this.multipartFile)));
} }
@Override @Override

View File

@@ -114,8 +114,8 @@ public class StandardServletMultipartResolver implements MultipartResolver {
@Override @Override
public void cleanupMultipart(MultipartHttpServletRequest request) { public void cleanupMultipart(MultipartHttpServletRequest request) {
if (!(request instanceof AbstractMultipartHttpServletRequest) || if (!(request instanceof AbstractMultipartHttpServletRequest abstractMultipartHttpServletRequest) ||
((AbstractMultipartHttpServletRequest) request).isResolved()) { abstractMultipartHttpServletRequest.isResolved()) {
// To be on the safe side: explicitly delete the parts, // To be on the safe side: explicitly delete the parts,
// but only actual file parts (for Resin compatibility) // but only actual file parts (for Resin compatibility)
try { try {

View File

@@ -247,8 +247,9 @@ public final class WebHttpHandlerBuilder {
List<WebFilter> filtersToUse = this.filters.stream() List<WebFilter> filtersToUse = this.filters.stream()
.peek(filter -> { .peek(filter -> {
if (filter instanceof ForwardedHeaderTransformer && this.forwardedHeaderTransformer == null) { if (filter instanceof ForwardedHeaderTransformer forwardedHeaderTransformerFilter
this.forwardedHeaderTransformer = (ForwardedHeaderTransformer) filter; && this.forwardedHeaderTransformer == null) {
this.forwardedHeaderTransformer = forwardedHeaderTransformerFilter;
} }
}) })
.filter(filter -> !(filter instanceof ForwardedHeaderTransformer)) .filter(filter -> !(filter instanceof ForwardedHeaderTransformer))

View File

@@ -95,8 +95,8 @@ public class ResponseStatusExceptionHandler implements WebExceptionHandler {
int code = (statusCode != null ? statusCode.value() : determineRawStatusCode(ex)); int code = (statusCode != null ? statusCode.value() : determineRawStatusCode(ex));
if (code != -1) { if (code != -1) {
if (response.setStatusCode(statusCode)) { if (response.setStatusCode(statusCode)) {
if (ex instanceof ResponseStatusException) { if (ex instanceof ResponseStatusException responseStatusException) {
((ResponseStatusException) ex).getHeaders().forEach((name, values) -> responseStatusException.getHeaders().forEach((name, values) ->
values.forEach(value -> response.getHeaders().add(name, value))); values.forEach(value -> response.getHeaders().add(name, value)));
} }
result = true; result = true;

View File

@@ -159,8 +159,8 @@ public abstract class ServletRequestPathUtils {
*/ */
public static String getCachedPathValue(ServletRequest request) { public static String getCachedPathValue(ServletRequest request) {
Object path = getCachedPath(request); Object path = getCachedPath(request);
if (path instanceof PathContainer) { if (path instanceof PathContainer pathContainer) {
String value = ((PathContainer) path).value(); String value = pathContainer.value();
path = UrlPathHelper.defaultInstance.removeSemicolonContent(value); path = UrlPathHelper.defaultInstance.removeSemicolonContent(value);
} }
return (String) path; return (String) path;

View File

@@ -726,8 +726,8 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable {
@Nullable @Nullable
private String getQueryParamValue(@Nullable Object value) { private String getQueryParamValue(@Nullable Object value) {
if (value != null) { if (value != null) {
return (value instanceof Optional ? return (value instanceof Optional<?> optionalValue ?
((Optional<?>) value).map(Object::toString).orElse(null) : optionalValue.map(Object::toString).orElse(null) :
value.toString()); value.toString());
} }
return null; return null;
@@ -741,8 +741,8 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable {
@Override @Override
public UriComponentsBuilder queryParamIfPresent(String name, Optional<?> value) { public UriComponentsBuilder queryParamIfPresent(String name, Optional<?> value) {
value.ifPresent(o -> { value.ifPresent(o -> {
if (o instanceof Collection) { if (o instanceof Collection<?> elements) {
queryParam(name, (Collection<?>) o); queryParam(name, elements);
} }
else { else {
queryParam(name, o); queryParam(name, o);

View File

@@ -66,8 +66,8 @@ class CaptureTheRestPathElement extends PathElement {
MultiValueMap<String,String> parametersCollector = null; MultiValueMap<String,String> parametersCollector = null;
for (int i = pathIndex; i < matchingContext.pathLength; i++) { for (int i = pathIndex; i < matchingContext.pathLength; i++) {
Element element = matchingContext.pathElements.get(i); Element element = matchingContext.pathElements.get(i);
if (element instanceof PathSegment) { if (element instanceof PathSegment pathSegment) {
MultiValueMap<String, String> parameters = ((PathSegment) element).parameters(); MultiValueMap<String, String> parameters = pathSegment.parameters();
if (!parameters.isEmpty()) { if (!parameters.isEmpty()) {
if (parametersCollector == null) { if (parametersCollector == null) {
parametersCollector = new LinkedMultiValueMap<>(); parametersCollector = new LinkedMultiValueMap<>();
@@ -86,8 +86,8 @@ class CaptureTheRestPathElement extends PathElement {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i = fromSegment, max = pathElements.size(); i < max; i++) { for (int i = fromSegment, max = pathElements.size(); i < max; i++) {
Element element = pathElements.get(i); Element element = pathElements.get(i);
if (element instanceof PathSegment) { if (element instanceof PathSegment pathSegment) {
sb.append(((PathSegment)element).valueToMatch()); sb.append(pathSegment.valueToMatch());
} }
else { else {
sb.append(element.value()); sb.append(element.value());