|
24 | 24 | import org.openrewrite.java.MethodMatcher; |
25 | 25 | import org.openrewrite.java.search.UsesJavaVersion; |
26 | 26 | import org.openrewrite.java.search.UsesMethod; |
27 | | -import org.openrewrite.java.tree.Expression; |
28 | 27 | import org.openrewrite.java.tree.J; |
29 | 28 |
|
30 | | -import java.util.List; |
31 | | -import java.util.StringJoiner; |
32 | | - |
33 | 29 | public class MigrateCollectionsUnmodifiableList extends Recipe { |
34 | 30 | private static final MethodMatcher UNMODIFIABLE_LIST = new MethodMatcher("java.util.Collections unmodifiableList(java.util.List)", true); |
35 | 31 | private static final MethodMatcher ARRAYS_AS_LIST = new MethodMatcher("java.util.Arrays asList(..)", true); |
@@ -59,15 +55,16 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) |
59 | 55 | maybeRemoveImport("java.util.Collections"); |
60 | 56 | maybeRemoveImport("java.util.Arrays"); |
61 | 57 | maybeAddImport("java.util.List"); |
62 | | - StringJoiner setOf = new StringJoiner(", ", "List.of(", ")"); |
63 | | - List<Expression> args = arraysInvocation.getArguments(); |
64 | | - args.forEach(o -> setOf.add("#{any()}")); |
65 | 58 |
|
66 | | - return JavaTemplate.builder(setOf.toString()) |
67 | | - .contextSensitive() |
| 59 | + // Build the List.of() invocation while preserving the original method's formatting |
| 60 | + J.MethodInvocation listOf = JavaTemplate.builder("List.of()") |
68 | 61 | .imports("java.util.List") |
69 | 62 | .build() |
70 | | - .apply(updateCursor(m), m.getCoordinates().replace(), args.toArray()); |
| 63 | + .apply(updateCursor(m), m.getCoordinates().replace()); |
| 64 | + |
| 65 | + // Replace the arguments while preserving their original formatting, comments, and padding |
| 66 | + return listOf.withArguments(arraysInvocation.getArguments()) |
| 67 | + .getPadding().withArguments(arraysInvocation.getPadding().getArguments()); |
71 | 68 | } |
72 | 69 | } |
73 | 70 | } |
|
0 commit comments