Skip to content

Commit

Permalink
do not modify when not Object::toString() (#118)
Browse files Browse the repository at this point in the history
  • Loading branch information
Joan Viladrosa authored Nov 7, 2023
1 parent 3140455 commit f0d296c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public Duration getEstimatedEffortPerOccurrence() {
}

private static final MethodMatcher STRING_VALUE_OF = new MethodMatcher("java.lang.String valueOf(..)");
private static final MethodMatcher OBJECT_TO_STRING = new MethodMatcher("java.lang.Object toString()");

@Override
public String getDisplayName() {
Expand Down Expand Up @@ -106,11 +107,11 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext execu
m = m.withSelect(method.getSelect());
return m;
}
} else if (args.get(0) instanceof J.MethodInvocation && "toString".equals(((J.MethodInvocation) args.get(0)).getSimpleName())) {
Expression valueOf = ((J.MethodInvocation) args.get(0)).getSelect();
if (valueOf != null) {
} else if (OBJECT_TO_STRING.matches(args.get(0))) {
Expression toString = ((J.MethodInvocation) args.get(0)).getSelect();
if (toString != null) {
J.MethodInvocation m = JavaTemplate.builder("\"{}\", #{any()}").contextSensitive().build()
.apply(getCursor(), method.getCoordinates().replaceArguments(), valueOf);
.apply(getCursor(), method.getCoordinates().replaceArguments(), toString);
m = m.withSelect(method.getSelect());
return m;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ void toStringWithoutSelect() {
java("""
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class A implements Cloneable {
class A {
private static final Logger log = LoggerFactory.getLogger(A.class);
public void foo() {
Expand Down Expand Up @@ -316,4 +316,52 @@ void method() {
);
}

@Test
void notObjectToString() {
//language=java
rewriteRun(
java("""
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
class A {
private static final Logger log = LoggerFactory.getLogger(A.class);
String[] values = new String[]{"test1", "test2"};
public void foo() {
log.error(Arrays.toString(values));
}
}
""")
);
}

@Test
void doNotUseToStringOnAnyClass() {
//language=java
rewriteRun(
java(
"""
import org.slf4j.Logger;
class Test {
Logger log;
void test() {
Test t = new Test();
log.info(t.toString());
}
}
""",
"""
import org.slf4j.Logger;
class Test {
Logger log;
void test() {
Test t = new Test();
log.info("{}", t);
}
}
"""
)
);
}

}

0 comments on commit f0d296c

Please sign in to comment.