Skip to content

Commit

Permalink
Strengthen override method determination for generic parameters (open…
Browse files Browse the repository at this point in the history
  • Loading branch information
jkschneider authored Jun 6, 2024
1 parent 7e1130c commit 5581192
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import org.junit.jupiter.api.Test;
import org.openrewrite.Issue;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;
Expand All @@ -30,18 +31,43 @@
@SuppressWarnings("ConstantConditions")
class JavaTypeTest implements RewriteTest {

@Test
void methodOverridesOfGenericParameters() {
rewriteRun(
java(
"""
class Test {
void test(java.util.List<Integer> l) {
l.add(0);
}
}
""",
spec -> spec.afterRecipe(cu -> new JavaIsoVisitor<Integer>() {
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Integer integer) {
MethodMatcher matcher = new MethodMatcher("java.util.List add(..)");
JavaType.Method methodType = method.getMethodType();
assertThat(matcher.matches(methodType)).isTrue();
assertThat(methodType.getOverride()).isNotNull();
return method;
}
}.visit(cu, 0))
)
);
}

@Test
void resolvedSignatureOfGenericMethodDeclarations() {
rewriteRun(
java(
"""
import java.util.ListIterator;
import static java.util.Collections.singletonList;
interface MyList<E> {
ListIterator<E> listIterator();
}
class Test {
ListIterator<Integer> s = singletonList(1).listIterator();
}
Expand Down Expand Up @@ -134,7 +160,7 @@ public class A {
void method() {
Test a = test(null);
}
Test test(Test test) {
return test;
}
Expand Down
18 changes: 16 additions & 2 deletions rewrite-java/src/main/java/org/openrewrite/java/tree/JavaType.java
Original file line number Diff line number Diff line change
Expand Up @@ -1228,8 +1228,22 @@ public JavaType.Method getOverride() {
continue;
}
for (int i = 0; i < params.size(); i++) {
if (!TypeUtils.isOfType(getParameterTypes().get(i), params.get(i))) {
continue nextMethod;
JavaType param = params.get(i);
JavaType subtypeParam = getParameterTypes().get(i);
if (!TypeUtils.isOfType(subtypeParam, param)) {
if (param instanceof GenericTypeVariable) {
GenericTypeVariable genericParam = (GenericTypeVariable) param;
if (genericParam.getBounds().isEmpty()) {
continue;
}
for (JavaType bound : genericParam.getBounds()) {
if (!TypeUtils.isAssignableTo(bound, subtypeParam)) {
continue nextMethod;
}
}
} else {
continue nextMethod;
}
}
}
return method;
Expand Down

0 comments on commit 5581192

Please sign in to comment.