|
33 | 33 | import org.openrewrite.java.tree.JavaType;
|
34 | 34 |
|
35 | 35 | import java.util.Collections;
|
| 36 | +import java.util.function.Function; |
36 | 37 | import java.util.Set;
|
37 | 38 |
|
38 | 39 | public class ReplaceClassIsInstanceWithInstanceof extends Recipe {
|
@@ -68,15 +69,29 @@ public J visitMethodInvocation(MethodInvocation method, ExecutionContext ctx) {
|
68 | 69 | FieldAccess fieldAccessPart = (FieldAccess) method.getSelect();
|
69 | 70 | // upcast to type J, so J.MethodInvocation can be replaced by J.InstanceOf
|
70 | 71 | JavaCoordinates coordinates = method.getCoordinates().replace();
|
71 |
| - J.InstanceOf instanceOf = JavaTemplate.builder("#{any()} instanceof Object") |
| 72 | + J updated = JavaTemplate.builder("#{any()} instanceof Object") |
72 | 73 | .build()
|
73 | 74 | .apply(getCursor(), coordinates, objectExpression);
|
74 |
| - instanceOf = instanceOf.withClazz(fieldAccessPart.getTarget().withPrefix(instanceOf.getClazz().getPrefix())); |
75 |
| - return maybeAutoFormat(method, instanceOf, ctx); |
| 75 | + updated = mapInstanceOf(updated, |
| 76 | + instanceOf -> instanceOf.withClazz(fieldAccessPart.getTarget().withPrefix(instanceOf.getClazz().getPrefix()))); |
| 77 | + return maybeAutoFormat(method, updated, ctx); |
76 | 78 | }
|
77 | 79 | return super.visitMethodInvocation(method, ctx);
|
78 | 80 | }
|
79 | 81 |
|
| 82 | + private J mapInstanceOf(J tree, Function<J.InstanceOf, J.InstanceOf> fun) { |
| 83 | + if (tree instanceof J.InstanceOf) { |
| 84 | + return fun.apply((J.InstanceOf) tree); |
| 85 | + } |
| 86 | + if (tree instanceof J.Parentheses) { |
| 87 | + J.Parentheses<J> par = (J.Parentheses<J>) tree; |
| 88 | + J inner = mapInstanceOf(par.getTree(), fun); |
| 89 | + return par.withTree(inner); |
| 90 | + } else { |
| 91 | + throw new IllegalArgumentException("Expected J.InstanceOf or J.Parentheses, but got: " + tree.getClass()); |
| 92 | + } |
| 93 | + } |
| 94 | + |
80 | 95 | private boolean isObjectClass(@Nullable Expression expression) {
|
81 | 96 | if (expression instanceof J.FieldAccess) {
|
82 | 97 | J.FieldAccess fieldAccess = (J.FieldAccess) expression;
|
|
0 commit comments