Skip to content

Commit

Permalink
Match JavaType.GenericTypeVariable in TypeUtils#isAssignableTo() (#…
Browse files Browse the repository at this point in the history
…3655)

Fix the assignability test for generic type variable types.
  • Loading branch information
knutwannheden committed Nov 2, 2023
1 parent 8bdf967 commit 30a74ee
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -245,4 +245,36 @@ public J.VariableDeclarations.NamedVariable visitVariable(J.VariableDeclarations
)
);
}

@Test
void isAssignableToGenericTypeVariable() {
rewriteRun(
java(
"""
import java.util.Map;
import java.util.function.Supplier;
class Test {
<K, V> void m(Supplier<? extends Map<K, ? extends V>> map) {
}
void foo() {
Map<String, Integer> map = null;
m(() -> map);
}
}
""",
spec -> spec.afterRecipe(cu -> new JavaIsoVisitor<>() {
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Object o) {
JavaType paramType = method.getMethodType().getParameterTypes().get(0);
assertThat(paramType).isInstanceOf(JavaType.Parameterized.class);
JavaType argType = method.getArguments().get(0).getType();
assertThat(argType).isInstanceOf(JavaType.Parameterized.class);
assertThat(TypeUtils.isAssignableTo(paramType, argType)).isTrue();
return method;
}
}.visit(cu, new InMemoryExecutionContext()))
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,12 @@ public static boolean isAssignableTo(@Nullable JavaType to, @Nullable JavaType f
JavaType.FullyQualified toFq = (JavaType.FullyQualified) to;
return isAssignableTo(toFq.getFullyQualifiedName(), from);
} else if (to instanceof JavaType.GenericTypeVariable) {
JavaType.GenericTypeVariable genericTo = (JavaType.GenericTypeVariable) to;
if (genericTo.getBounds().isEmpty()) {
return genericTo.getName().equals("?");
JavaType.GenericTypeVariable toGeneric = (JavaType.GenericTypeVariable) to;
List<JavaType> toBounds = toGeneric.getBounds();
if (toBounds.isEmpty()) {
return toGeneric.getName().equals("?");
} else if (toBounds.size() == 1) {
return isAssignableTo(toBounds.get(0), from);
}
return false;
} else if (to instanceof JavaType.Variable) {
Expand Down

0 comments on commit 30a74ee

Please sign in to comment.