Apply "instanceof pattern matching" in spring-webflux

Closes gh-29635
This commit is contained in:
divcon 2022-12-04 22:33:45 +09:00 committed by Sam Brannen
parent 918edaba2e
commit f64397d822
22 changed files with 68 additions and 70 deletions

View File

@ -148,8 +148,8 @@ public class ResourceHandlerRegistry {
private ResourceWebHandler getRequestHandler(ResourceHandlerRegistration registration) { private ResourceWebHandler getRequestHandler(ResourceHandlerRegistration registration) {
ResourceWebHandler handler = registration.getRequestHandler(); ResourceWebHandler handler = registration.getRequestHandler();
for (ResourceTransformer transformer : handler.getResourceTransformers()) { for (ResourceTransformer transformer : handler.getResourceTransformers()) {
if (transformer instanceof ResourceTransformerSupport) { if (transformer instanceof ResourceTransformerSupport resourceTransformerSupport) {
((ResourceTransformerSupport) transformer).setResourceUrlProvider(this.resourceUrlProvider); resourceTransformerSupport.setResourceUrlProvider(this.resourceUrlProvider);
} }
} }
try { try {

View File

@ -363,8 +363,8 @@ public abstract class BodyInserters {
M outputMessage, BodyInserter.Context context, Object body, ResolvableType bodyType, @Nullable ReactiveAdapter adapter) { M outputMessage, BodyInserter.Context context, Object body, ResolvableType bodyType, @Nullable ReactiveAdapter adapter) {
Publisher<?> publisher; Publisher<?> publisher;
if (body instanceof Publisher) { if (body instanceof Publisher<?> publisherBody) {
publisher = (Publisher<?>) body; publisher = publisherBody;
} }
else if (adapter != null) { else if (adapter != null) {
publisher = adapter.toPublisher(body); publisher = adapter.toPublisher(body);

View File

@ -133,11 +133,11 @@ class DefaultClientResponse implements ClientResponse {
public <T> T body(BodyExtractor<T, ? super ClientHttpResponse> extractor) { public <T> T body(BodyExtractor<T, ? super ClientHttpResponse> extractor) {
T result = extractor.extract(this.response, this.bodyExtractorContext); T result = extractor.extract(this.response, this.bodyExtractorContext);
String description = "Body from " + this.requestDescription + " [DefaultClientResponse]"; String description = "Body from " + this.requestDescription + " [DefaultClientResponse]";
if (result instanceof Mono) { if (result instanceof Mono<?> monoResult) {
return (T) ((Mono<?>) result).checkpoint(description); return (T) monoResult.checkpoint(description);
} }
else if (result instanceof Flux) { else if (result instanceof Flux<?> fluxResult) {
return (T) ((Flux<?>) result).checkpoint(description); return (T) fluxResult.checkpoint(description);
} }
else { else {
return result; return result;

View File

@ -107,7 +107,7 @@ final class DefaultRenderingResponseBuilder implements RenderingResponse.Builder
@Override @Override
public RenderingResponse.Builder modelAttribute(Object attribute) { public RenderingResponse.Builder modelAttribute(Object attribute) {
Assert.notNull(attribute, "Attribute must not be null"); Assert.notNull(attribute, "Attribute must not be null");
if (attribute instanceof Collection && ((Collection<?>) attribute).isEmpty()) { if (attribute instanceof Collection<?> attrCollection && attrCollection.isEmpty()) {
return this; return this;
} }
return modelAttribute(Conventions.getVariableName(attribute), attribute); return modelAttribute(Conventions.getVariableName(attribute), attribute);

View File

@ -129,8 +129,8 @@ class PathResourceLookupFunction implements Function<ServerRequest, Mono<Resourc
resourcePath = resource.getURL().toExternalForm(); resourcePath = resource.getURL().toExternalForm();
locationPath = StringUtils.cleanPath(this.location.getURL().toString()); locationPath = StringUtils.cleanPath(this.location.getURL().toString());
} }
else if (resource instanceof ClassPathResource) { else if (resource instanceof ClassPathResource classPathResource) {
resourcePath = ((ClassPathResource) resource).getPath(); resourcePath = classPathResource.getPath();
locationPath = StringUtils.cleanPath(((ClassPathResource) this.location).getPath()); locationPath = StringUtils.cleanPath(((ClassPathResource) this.location).getPath());
} }
else { else {

View File

@ -795,11 +795,11 @@ public abstract class RequestPredicates {
@Override @Override
public void changeParser(PathPatternParser parser) { public void changeParser(PathPatternParser parser) {
if (this.left instanceof ChangePathPatternParserVisitor.Target) { if (this.left instanceof ChangePathPatternParserVisitor.Target leftTarget) {
((ChangePathPatternParserVisitor.Target) this.left).changeParser(parser); leftTarget.changeParser(parser);
} }
if (this.right instanceof ChangePathPatternParserVisitor.Target) { if (this.right instanceof ChangePathPatternParserVisitor.Target rightTarget) {
((ChangePathPatternParserVisitor.Target) this.right).changeParser(parser); rightTarget.changeParser(parser);
} }
} }
@ -841,8 +841,8 @@ public abstract class RequestPredicates {
@Override @Override
public void changeParser(PathPatternParser parser) { public void changeParser(PathPatternParser parser) {
if (this.delegate instanceof ChangePathPatternParserVisitor.Target) { if (this.delegate instanceof ChangePathPatternParserVisitor.Target target) {
((ChangePathPatternParserVisitor.Target) this.delegate).changeParser(parser); target.changeParser(parser);
} }
} }
@ -909,11 +909,11 @@ public abstract class RequestPredicates {
@Override @Override
public void changeParser(PathPatternParser parser) { public void changeParser(PathPatternParser parser) {
if (this.left instanceof ChangePathPatternParserVisitor.Target) { if (this.left instanceof ChangePathPatternParserVisitor.Target leftTarget) {
((ChangePathPatternParserVisitor.Target) this.left).changeParser(parser); leftTarget.changeParser(parser);
} }
if (this.right instanceof ChangePathPatternParserVisitor.Target) { if (this.right instanceof ChangePathPatternParserVisitor.Target rightTarget) {
((ChangePathPatternParserVisitor.Target) this.right).changeParser(parser); rightTarget.changeParser(parser);
} }
} }

View File

@ -233,8 +233,8 @@ public abstract class AbstractHandlerMapping extends ApplicationObjectSupport
*/ */
@Nullable @Nullable
protected CorsConfiguration getCorsConfiguration(Object handler, ServerWebExchange exchange) { protected CorsConfiguration getCorsConfiguration(Object handler, ServerWebExchange exchange) {
if (handler instanceof CorsConfigurationSource) { if (handler instanceof CorsConfigurationSource ccs) {
return ((CorsConfigurationSource) handler).getCorsConfiguration(exchange); return ccs.getCorsConfiguration(exchange);
} }
return null; return null;
} }

View File

@ -153,8 +153,8 @@ public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping {
url = "/" + url; url = "/" + url;
} }
// Remove whitespace from handler bean name. // Remove whitespace from handler bean name.
if (handler instanceof String) { if (handler instanceof String handlerName) {
handler = ((String) handler).trim(); handler = handlerName.trim();
} }
registerHandler(url, handler); registerHandler(url, handler);
} }

View File

@ -272,8 +272,8 @@ public class EncodedResourceResolver extends AbstractResourceResolver {
@Override @Override
public HttpHeaders getResponseHeaders() { public HttpHeaders getResponseHeaders() {
HttpHeaders headers; HttpHeaders headers;
if (this.original instanceof HttpResource) { if (this.original instanceof HttpResource httpResource) {
headers = ((HttpResource) this.original).getResponseHeaders(); headers = httpResource.getResponseHeaders();
} }
else { else {
headers = new HttpHeaders(); headers = new HttpHeaders();

View File

@ -247,7 +247,7 @@ public class ModelAttributeMethodArgumentResolver extends HandlerMethodArgumentR
} }
} }
} }
value = (value instanceof List ? ((List<?>) value).toArray() : value); value = (value instanceof List<?> valueList ? valueList.toArray() : value);
MethodParameter methodParam = new MethodParameter(ctor, i); MethodParameter methodParam = new MethodParameter(ctor, i);
if (value == null && methodParam.isOptional()) { if (value == null && methodParam.isOptional()) {
args[i] = (methodParam.getParameterType() == Optional.class ? Optional.empty() : null); args[i] = (methodParam.getParameterType() == Optional.class ? Optional.empty() : null);

View File

@ -177,8 +177,8 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi
@Nullable @Nullable
private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) { private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class); RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
RequestCondition<?> condition = (element instanceof Class ? RequestCondition<?> condition = (element instanceof Class<?> typeElement ?
getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element)); getCustomTypeCondition(typeElement) : getCustomMethodCondition((Method) element));
return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null); return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
} }

View File

@ -137,8 +137,8 @@ public class ResponseEntityResultHandler extends AbstractMessageWriterResultHand
return returnValueMono.flatMap(returnValue -> { return returnValueMono.flatMap(returnValue -> {
HttpEntity<?> httpEntity; HttpEntity<?> httpEntity;
if (returnValue instanceof HttpEntity) { if (returnValue instanceof HttpEntity<?> he) {
httpEntity = (HttpEntity<?>) returnValue; httpEntity = he;
} }
else if (returnValue instanceof ErrorResponse response) { else if (returnValue instanceof ErrorResponse response) {
httpEntity = new ResponseEntity<>(response.getBody(), response.getHeaders(), response.getStatusCode()); httpEntity = new ResponseEntity<>(response.getBody(), response.getHeaders(), response.getStatusCode());
@ -146,8 +146,8 @@ public class ResponseEntityResultHandler extends AbstractMessageWriterResultHand
else if (returnValue instanceof ProblemDetail detail) { else if (returnValue instanceof ProblemDetail detail) {
httpEntity = ResponseEntity.of(detail).build(); httpEntity = ResponseEntity.of(detail).build();
} }
else if (returnValue instanceof HttpHeaders) { else if (returnValue instanceof HttpHeaders headers) {
httpEntity = new ResponseEntity<>((HttpHeaders) returnValue, HttpStatus.OK); httpEntity = new ResponseEntity<>(headers, HttpStatus.OK);
} }
else { else {
throw new IllegalArgumentException( throw new IllegalArgumentException(

View File

@ -124,8 +124,8 @@ public class ServerWebExchangeMethodArgumentResolver extends HandlerMethodArgume
@Nullable @Nullable
private TimeZone getTimeZone(LocaleContext localeContext) { private TimeZone getTimeZone(LocaleContext localeContext) {
TimeZone timeZone = null; TimeZone timeZone = null;
if (localeContext instanceof TimeZoneAwareLocaleContext) { if (localeContext instanceof TimeZoneAwareLocaleContext timeZoneAwareLocaleContext) {
timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone(); timeZone = timeZoneAwareLocaleContext.getTimeZone();
} }
return timeZone; return timeZone;
} }

View File

@ -126,8 +126,8 @@ public class BindStatus {
this.objectErrors = this.errors.getFieldErrors(this.expression); this.objectErrors = this.errors.getFieldErrors(this.expression);
this.value = this.errors.getFieldValue(this.expression); this.value = this.errors.getFieldValue(this.expression);
this.valueType = this.errors.getFieldType(this.expression); this.valueType = this.errors.getFieldType(this.expression);
if (this.errors instanceof BindingResult) { if (this.errors instanceof BindingResult bindingResultError) {
this.bindingResult = (BindingResult) this.errors; this.bindingResult = bindingResultError;
this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.actualValue = this.bindingResult.getRawFieldValue(this.expression);
this.editor = this.bindingResult.findEditor(this.expression, null); this.editor = this.bindingResult.findEditor(this.expression, null);
} }
@ -162,8 +162,8 @@ public class BindStatus {
this.errorMessages = new String[0]; this.errorMessages = new String[0];
} }
if (htmlEscape && this.value instanceof String) { if (htmlEscape && this.value instanceof String valueString) {
this.value = HtmlUtils.htmlEscape((String) this.value); this.value = HtmlUtils.htmlEscape(valueString);
} }
} }
@ -238,8 +238,8 @@ public class BindStatus {
* will get HTML-escaped. * will get HTML-escaped.
*/ */
public String getDisplayValue() { public String getDisplayValue() {
if (this.value instanceof String) { if (this.value instanceof String stringValue) {
return (String) this.value; return stringValue;
} }
if (this.value != null) { if (this.value != null) {
return (this.htmlEscape ? return (this.htmlEscape ?

View File

@ -324,8 +324,8 @@ public class UrlBasedViewResolver extends ViewResolverSupport
ApplicationContext context = getApplicationContext(); ApplicationContext context = getApplicationContext();
if (context != null) { if (context != null) {
Object initialized = context.getAutowireCapableBeanFactory().initializeBean(view, viewName); Object initialized = context.getAutowireCapableBeanFactory().initializeBean(view, viewName);
if (initialized instanceof View) { if (initialized instanceof View initializedView) {
return (View) initialized; return initializedView;
} }
} }
return view; return view;

View File

@ -223,7 +223,7 @@ public class ViewResolutionResultHandler extends HandlerResultHandlerSupport imp
if (view == null) { if (view == null) {
view = getDefaultViewName(exchange); view = getDefaultViewName(exchange);
} }
viewsMono = (view instanceof String ? resolveViews((String) view, locale) : viewsMono = (view instanceof String stringView? resolveViews(stringView, locale) :
Mono.just(Collections.singletonList((View) view))); Mono.just(Collections.singletonList((View) view)));
} }
else if (Model.class.isAssignableFrom(clazz)) { else if (Model.class.isAssignableFrom(clazz)) {

View File

@ -164,8 +164,8 @@ public class HandshakeWebSocketService implements WebSocketService, Lifecycle {
} }
protected void doStart() { protected void doStart() {
if (getUpgradeStrategy() instanceof Lifecycle) { if (getUpgradeStrategy() instanceof Lifecycle lifecycle) {
((Lifecycle) getUpgradeStrategy()).start(); lifecycle.start();
} }
} }
@ -178,8 +178,8 @@ public class HandshakeWebSocketService implements WebSocketService, Lifecycle {
} }
protected void doStop() { protected void doStop() {
if (getUpgradeStrategy() instanceof Lifecycle) { if (getUpgradeStrategy() instanceof Lifecycle lifecycle) {
((Lifecycle) getUpgradeStrategy()).stop(); lifecycle.stop();
} }
} }

View File

@ -84,8 +84,8 @@ class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTes
private ReactorClientHttpConnector initConnector() { private ReactorClientHttpConnector initConnector() {
assertThat(super.bufferFactory).isNotNull(); assertThat(super.bufferFactory).isNotNull();
if (super.bufferFactory instanceof NettyDataBufferFactory) { if (super.bufferFactory instanceof NettyDataBufferFactory nettyDataBufferFactory) {
ByteBufAllocator allocator = ((NettyDataBufferFactory) super.bufferFactory).getByteBufAllocator(); ByteBufAllocator allocator = nettyDataBufferFactory.getByteBufAllocator();
return new ReactorClientHttpConnector(this.factory, return new ReactorClientHttpConnector(this.factory,
client -> client.option(ChannelOption.ALLOCATOR, allocator)); client -> client.option(ChannelOption.ALLOCATOR, allocator));
} }

View File

@ -144,8 +144,8 @@ public final class Msg extends
*/ */
public String getFoo() { public String getFoo() {
Object ref = foo_; Object ref = foo_;
if (ref instanceof String) { if (ref instanceof String stringRef) {
return (String) ref; return stringRef;
} else { } else {
com.google.protobuf.ByteString bs = com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref; (com.google.protobuf.ByteString) ref;
@ -162,10 +162,9 @@ public final class Msg extends
public com.google.protobuf.ByteString public com.google.protobuf.ByteString
getFooBytes() { getFooBytes() {
Object ref = foo_; Object ref = foo_;
if (ref instanceof String) { if (ref instanceof String stringRef) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8( com.google.protobuf.ByteString.copyFromUtf8(stringRef);
(String) ref);
foo_ = b; foo_ = b;
return b; return b;
} else { } else {
@ -405,8 +404,8 @@ public final class Msg extends
} }
public Builder mergeFrom(com.google.protobuf.Message other) { public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Msg) { if (other instanceof Msg msg) {
return mergeFrom((Msg)other); return mergeFrom(msg);
} else { } else {
super.mergeFrom(other); super.mergeFrom(other);
return this; return this;
@ -463,13 +462,13 @@ public final class Msg extends
*/ */
public String getFoo() { public String getFoo() {
Object ref = foo_; Object ref = foo_;
if (!(ref instanceof String)) { if (!(ref instanceof String stringRef)) {
String s = ((com.google.protobuf.ByteString) ref) String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8(); .toStringUtf8();
foo_ = s; foo_ = s;
return s; return s;
} else { } else {
return (String) ref; return stringRef;
} }
} }
/** /**
@ -478,10 +477,9 @@ public final class Msg extends
public com.google.protobuf.ByteString public com.google.protobuf.ByteString
getFooBytes() { getFooBytes() {
Object ref = foo_; Object ref = foo_;
if (ref instanceof String) { if (ref instanceof String stringRef) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8( com.google.protobuf.ByteString.copyFromUtf8(stringRef);
(String) ref);
foo_ = b; foo_ = b;
return b; return b;
} else { } else {

View File

@ -304,8 +304,8 @@ public final class SecondMsg extends
} }
public Builder mergeFrom(com.google.protobuf.Message other) { public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof SecondMsg) { if (other instanceof SecondMsg secondMsg) {
return mergeFrom((SecondMsg)other); return mergeFrom(secondMsg);
} else { } else {
super.mergeFrom(other); super.mergeFrom(other);
return this; return this;

View File

@ -354,7 +354,7 @@ class MultipartIntegrationTests extends AbstractHttpHandlerIntegrationTests {
} }
private static String partDescription(Part part) { private static String partDescription(Part part) {
return part instanceof FilePart ? part.name() + ":" + ((FilePart) part).filename() : part.name(); return part instanceof FilePart filePart? part.name() + ":" + filePart.filename() : part.name();
} }
static class FormBean { static class FormBean {

View File

@ -142,15 +142,15 @@ abstract class AbstractReactiveWebSocketIntegrationTests {
// Set dynamically chosen port // Set dynamically chosen port
this.port = this.server.getPort(); this.port = this.server.getPort();
if (this.client instanceof Lifecycle) { if (this.client instanceof Lifecycle lifecycle) {
((Lifecycle) this.client).start(); lifecycle.start();
} }
} }
@AfterEach @AfterEach
void stopServer() { void stopServer() {
if (this.client instanceof Lifecycle) { if (this.client instanceof Lifecycle lifecycle) {
((Lifecycle) this.client).stop(); lifecycle.stop();
} }
this.server.stop(); this.server.stop();
} }