Skip to content

Commit 28b02de

Browse files
authored
Limit RemoveSystemOutPrintln to System.out and System.err (#770)
1 parent 475af6c commit 28b02de

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

src/main/java/org/openrewrite/staticanalysis/RemoveSystemOutPrintln.java

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import org.openrewrite.java.tree.J;
2727
import org.openrewrite.java.tree.JRightPadded;
2828
import org.openrewrite.java.tree.Space;
29+
import org.openrewrite.java.tree.TypeUtils;
2930
import org.openrewrite.marker.Markers;
3031

3132
import static java.util.Collections.emptyList;
@@ -41,7 +42,8 @@ public String getDisplayName() {
4142

4243
@Override
4344
public String getDescription() {
44-
return "Print statements are often left accidentally after debugging an issue.";
45+
return "Print statements are often left accidentally after debugging an issue. " +
46+
"This recipe removes all `System.out#println` and `System.err#println` statements from the code.";
4547
}
4648

4749
@Override
@@ -60,8 +62,11 @@ public J.Lambda visitLambda(J.Lambda lambda, ExecutionContext ctx) {
6062

6163
@Override
6264
@SuppressWarnings("NullableProblems")
63-
public J.@Nullable MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
64-
if (SYSTEM_OUT_PRINTLN.matches(method)) {
65+
public J.@Nullable MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
66+
if (SYSTEM_OUT_PRINTLN.matches(method) &&
67+
method.getSelect() instanceof J.FieldAccess &&
68+
(((J.FieldAccess) method.getSelect()).getTarget() instanceof J.Identifier &&
69+
TypeUtils.isAssignableTo("java.lang.System", ((J.FieldAccess) method.getSelect()).getTarget().getType()))) {
6570
return null;
6671
}
6772
return super.visitMethodInvocation(method, ctx);

src/test/java/org/openrewrite/staticanalysis/RemoveSystemOutPrintlnTest.java

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,30 @@ void removePrintln() {
3636
//language=java
3737
java(
3838
"""
39+
import java.io.PrintStream;
40+
3941
class Test {
40-
void test() {
42+
void printOut() {
4143
System.out.println("Hello, world!");
4244
}
45+
void printErr() {
46+
System.err.println("Hello, world!");
47+
}
48+
void printStream(PrintStream printStream) {
49+
printStream.println("Hello, world!");
50+
}
4351
}
4452
""",
4553
"""
54+
import java.io.PrintStream;
55+
4656
class Test {
47-
void test() {
57+
void printOut() {
58+
}
59+
void printErr() {
60+
}
61+
void printStream(PrintStream printStream) {
62+
printStream.println("Hello, world!");
4863
}
4964
}
5065
"""

0 commit comments

Comments
 (0)