Skip to content

Commit 99059a5

Browse files
author
Tim te Beek
authored
Maybe remove static import String.format & do not wrap method invocation (#120)
1 parent a300600 commit 99059a5

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/main/java/org/openrewrite/java/migrate/lang/StringFormatted.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,11 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext p) {
6464

6565
List<Expression> arguments = mi.getArguments();
6666
String template = String.format(
67-
arguments.get(0) instanceof J.Literal
67+
arguments.get(0) instanceof J.Literal || arguments.get(0) instanceof J.MethodInvocation
6868
? "#{any(java.lang.String)}.formatted(%s)"
6969
: "(#{any(java.lang.String)}).formatted(%s)",
7070
String.join(", ", Collections.nCopies(arguments.size() - 1, "#{any()}")));
71+
maybeRemoveImport("java.lang.String.format");
7172
return mi.withTemplate(
7273
JavaTemplate.builder(this::getCursor, template)
7374
.javaParser(() -> JavaParser.fromJavaVersion().build())

src/test/kotlin/org/openrewrite/java/migrate/lang/StringFormattedTest.kt

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,4 +118,41 @@ class StringFormattedTest : RewriteTest {
118118
""")
119119
)
120120

121+
@Test
122+
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/77")
123+
fun doNotWrapMethodInvocation() = rewriteRun(
124+
java("""
125+
class A {
126+
String str = String.format(someMethod(), "a");
127+
String someMethod() {
128+
return "foo %s";
129+
}
130+
}
131+
""",
132+
"""
133+
class A {
134+
String str = someMethod().formatted("a");
135+
String someMethod() {
136+
return "foo %s";
137+
}
138+
}
139+
""")
140+
)
141+
142+
@Test
143+
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/77")
144+
fun removeStaticImport() = rewriteRun(
145+
java("""
146+
import static java.lang.String.format;
147+
class A {
148+
String str = format("foo %s", "a");
149+
}
150+
""",
151+
"""
152+
class A {
153+
String str = "foo %s".formatted("a");
154+
}
155+
""")
156+
)
157+
121158
}

0 commit comments

Comments
 (0)