Skip to content

Commit

Permalink
Don't use static import on collision with local method (#3729)
Browse files Browse the repository at this point in the history
If a class declares a method with the same name as a candidate for a static import, then that will always lead to compile errors if the static import is applied. Therefore the recipe must check for not having any similarly named method locally.
  • Loading branch information
Bananeweizen authored Nov 22, 2023
1 parent d9ea65b commit aa84b61
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,29 @@ public void methodWithTypeParameter() {
)
);
}

@Test
void sameMethodLocallyNoStaticImport() {
rewriteRun(
spec -> spec.recipe(new UseStaticImport("java.util.Collections emptyList()")),
java(
"""
import java.util.Collections;
import java.util.List;
public class SameMethodNameLocally {
public void avoidCollision() {
List<Object> list = Collections.emptyList();
}
private int emptyList(String canHaveDifferentArguments) {
}
}
"""
)
);
}

@Test
void methodInvocationsHavingNullSelect() {
rewriteRun(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import lombok.*;
import lombok.experimental.FieldDefaults;
import org.openrewrite.*;
import org.openrewrite.java.search.DeclaresMethod;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
Expand Down Expand Up @@ -50,7 +51,10 @@ public String getDescription() {

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesMethod<>(methodPattern), new UseStaticImportVisitor());
int indexSpace = methodPattern.indexOf(' ');
int indexBrace = methodPattern.indexOf('(', indexSpace);
String identicalMethodName = "* " + methodPattern.substring(indexSpace, indexBrace) + "(..)";
return Preconditions.check(Preconditions.and(new UsesMethod<>(methodPattern), Preconditions.not(new DeclaresMethod<>(identicalMethodName))), new UseStaticImportVisitor());
}

private class UseStaticImportVisitor extends JavaIsoVisitor<ExecutionContext> {
Expand Down

0 comments on commit aa84b61

Please sign in to comment.