Skip to content

Commit

Permalink
ChangeMethodTargetToStatic should also change instance usage
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek committed May 19, 2024
1 parent 2ae80bc commit 128d061
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,45 @@ public void test() {
);
}

@Test
void staticMethodCalledOnInstanceToCallOnClass() {
rewriteRun(
spec -> spec.recipe(new ChangeMethodTargetToStatic("a.A method()", "a.A", null, null)),
java(
"""
package a;
public class A {
public static void method() {}
}
"""
),
java(
"""
import a.A;
class Test {
public void test() {
A.method();
new A().method();
A a = new A();
a.method();
}
}
""",
"""
import a.A;
class Test {
public void test() {
A.method();
A.method();
A a = new A();
A.method();
}
}
"""
)
);
}

@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
@Issue("https://github.com/openrewrite/rewrite/issues/3085")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,12 @@ public ChangeMethodTargetToStaticVisitor(MethodMatcher methodMatcher, boolean ma
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation m = super.visitMethodInvocation(method, ctx);
Expression select = method.getSelect();
boolean isStatic = method.getMethodType() != null && method.getMethodType().hasFlags(Flag.Static);
boolean isSameReceiverType = method.getSelect() != null &&
TypeUtils.isOfClassType(method.getSelect().getType(), fullyQualifiedTargetTypeName);

if ((!isStatic || !isSameReceiverType) && methodMatcher.matches(method, matchUnknownTypes)) {
boolean isSameReceiverType = select != null && TypeUtils.isOfClassType(select.getType(), fullyQualifiedTargetTypeName);
boolean calledOnTargetType = select instanceof J.Identifier && ((J.Identifier) select).getFieldType() == null;
if ((!isStatic || !isSameReceiverType || !calledOnTargetType) &&
methodMatcher.matches(method, matchUnknownTypes)) {
JavaType.Method transformedType = null;
if (method.getMethodType() != null) {
maybeRemoveImport(method.getMethodType().getDeclaringType());
Expand All @@ -138,9 +139,9 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
maybeAddImport(fullyQualifiedTargetTypeName, !matchUnknownTypes);
m = method.withSelect(
new J.Identifier(randomId(),
method.getSelect() == null ?
select == null ?
Space.EMPTY :
method.getSelect().getPrefix(),
select.getPrefix(),
Markers.EMPTY,
emptyList(),
classType.getClassName(),
Expand Down

0 comments on commit 128d061

Please sign in to comment.