|
24 | 24 | import org.openrewrite.java.JavaIsoVisitor; |
25 | 25 | import org.openrewrite.java.JavaVisitor; |
26 | 26 | import org.openrewrite.java.JavadocVisitor; |
| 27 | +import org.openrewrite.java.MethodMatcher; |
27 | 28 | import org.openrewrite.java.tree.*; |
28 | 29 |
|
29 | 30 | import java.util.Comparator; |
@@ -121,17 +122,38 @@ private void removeThrownTypes(JavaType.@Nullable Method type) { |
121 | 122 | } |
122 | 123 | } |
123 | 124 | } |
124 | | - }.visit(m, ctx); |
| 125 | + }.visit(m, ctx, getCursor().getParent()); |
125 | 126 |
|
126 | 127 | if (!unusedThrows.isEmpty()) { |
| 128 | + MethodMatcher originalMethodMatcher = new MethodMatcher(m); |
| 129 | + |
| 130 | + JavaType.Method replacementMethodType = m.getMethodType().withThrownExceptions(ListUtils.map(m.getMethodType().getThrownExceptions(), t -> { |
| 131 | + JavaType.FullyQualified type = TypeUtils.asFullyQualified(t); |
| 132 | + return type != null && unusedThrows.contains(type) ? null : t; |
| 133 | + })); |
127 | 134 | m = m.withThrows(ListUtils.map(m.getThrows(), t -> { |
128 | | - JavaType.FullyQualified type = TypeUtils.asFullyQualified(t.getType()); |
129 | | - if (type != null && unusedThrows.contains(type)) { |
130 | | - maybeRemoveImport(type); |
131 | | - return null; |
| 135 | + JavaType.FullyQualified type = TypeUtils.asFullyQualified(t.getType()); |
| 136 | + if (type != null && unusedThrows.contains(type)) { |
| 137 | + maybeRemoveImport(type); |
| 138 | + return null; |
| 139 | + } |
| 140 | + return t; |
| 141 | + })) |
| 142 | + .withMethodType(replacementMethodType) |
| 143 | + .withName(m.getName().withType(replacementMethodType)); |
| 144 | + |
| 145 | + // Remove the thrown exceptions from the method type, such that UnnecessaryCatch can continue |
| 146 | + doAfterVisit(new JavaIsoVisitor<ExecutionContext>() { |
| 147 | + @Override |
| 148 | + public J.MethodInvocation visitMethodInvocation(J.MethodInvocation invocation, ExecutionContext ctx) { |
| 149 | + if (originalMethodMatcher.matches(invocation)) { |
| 150 | + invocation = invocation.withMethodType(replacementMethodType) |
| 151 | + .withName(invocation.getName().withType(replacementMethodType)); |
| 152 | + } |
| 153 | + return super.visitMethodInvocation(invocation, ctx); |
132 | 154 | } |
133 | | - return t; |
134 | | - })); |
| 155 | + }); |
| 156 | + doAfterVisit(new UnnecessaryCatch(true, false).getVisitor()); |
135 | 157 | } |
136 | 158 | } |
137 | 159 |
|
|
0 commit comments