diff --git a/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForGenericMethodInvocations.java b/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForGenericMethodInvocations.java index f8990a5e2f..2909bc73cf 100644 --- a/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForGenericMethodInvocations.java +++ b/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForGenericMethodInvocations.java @@ -117,7 +117,7 @@ private J.MethodInvocation makeNestedGenericsExplicit(J.MethodInvocation mi, J.V } // Add explicit type parameters when the method is generic and the return type's type parameter matches a type parameter from the declaring class - if (mi.getTypeParameters() == null && mi.getMethodType() != null && containsGenericTypeVariable(mi.getMethodType().getReturnType())) { + if (mi.getTypeParameters() == null && mi.getMethodType() != null && containsGenericTypeVariable(mi.getMethodType().getReturnType()) && !containsWildcard(leftTypeParams)) { // Create JRightPadded list from leftTypeParams List> typeParamsList = new ArrayList<>(); for (Expression typeParam : leftTypeParams) { @@ -141,6 +141,15 @@ private J.MethodInvocation makeNestedGenericsExplicit(J.MethodInvocation mi, J.V })); } + private static boolean containsWildcard(List typeParams) { + for (Expression typeParam : typeParams) { + if (typeParam instanceof J.Wildcard) { + return true; + } + } + return false; + } + private boolean containsGenericTypeVariable(JavaType type) { if (type instanceof JavaType.GenericTypeVariable) { return true; diff --git a/src/test/java/org/openrewrite/java/migrate/lang/var/UseVarForGenericMethodInvocationsTest.java b/src/test/java/org/openrewrite/java/migrate/lang/var/UseVarForGenericMethodInvocationsTest.java index 0d56e51a8a..86061f3b52 100644 --- a/src/test/java/org/openrewrite/java/migrate/lang/var/UseVarForGenericMethodInvocationsTest.java +++ b/src/test/java/org/openrewrite/java/migrate/lang/var/UseVarForGenericMethodInvocationsTest.java @@ -425,6 +425,32 @@ void m() { ); } + @Test + void wildcardTypeParameterNoExplicitTypeArgument() { + //language=java + rewriteRun( + version( + java( + """ + class A { + void m(ClassLoader cl) throws Exception { + Class recipeClass = cl.loadClass("java.lang.String"); + } + } + """, + """ + class A { + void m(ClassLoader cl) throws Exception { + var recipeClass = cl.loadClass("java.lang.String"); + } + } + """ + ), + 10 + ) + ); + } + @Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/868") @Test void genericsCollectorsRegression() {