2929import org .openrewrite .java .search .UsesMethod ;
3030import org .openrewrite .java .tree .Expression ;
3131import org .openrewrite .java .tree .J ;
32+ import org .openrewrite .java .tree .JavaType ;
3233import org .openrewrite .java .tree .Statement ;
3334import org .openrewrite .java .tree .TypeUtils ;
3435
@@ -78,7 +79,9 @@ public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) {
7879 new StringJoiner (", " , "Map.ofEntries(" , ")" ) :
7980 new StringJoiner (", " , "Map.of(" , ")" );
8081 for (J .MethodInvocation put : puts ) {
81- args .addAll (put .getArguments ());
82+ for (Expression arg : put .getArguments ()) {
83+ args .add (arg .unwrap ());
84+ }
8285 if (useEntries ) {
8386 inner .add ("Map.entry(#{any()}, #{any()})" );
8487 } else {
@@ -317,7 +320,7 @@ private String matchingTargetName(J.VariableDeclarations decl) {
317320 /**
318321 * If {@code stmt} is {@code targetName.put(k, v)} matching {@link #MAP_PUT},
319322 * returns [key, value] as a list; otherwise {@code null}. Returns {@code null}
320- * if either argument is the {@code null} literal , since {@code Map.of(..)} and
323+ * unless both arguments are proven non- null, since {@code Map.of(..)} and
321324 * {@code Map.entry(..)} reject nulls.
322325 */
323326 private List <Expression > matchPutCallOn (Statement stmt , String targetName ) {
@@ -338,13 +341,35 @@ private List<Expression> matchPutCallOn(Statement stmt, String targetName) {
338341 return null ;
339342 }
340343 for (Expression arg : mi .getArguments ()) {
341- if (J . Literal . isLiteralValue ( arg , null )) {
344+ if (! isProvablyNonNull ( arg )) {
342345 return null ;
343346 }
344347 }
345348 return mi .getArguments ();
346349 }
347350
351+ private boolean isProvablyNonNull (Expression expression ) {
352+ expression = expression .unwrap ();
353+ if (expression instanceof J .Literal ) {
354+ return !J .Literal .isLiteralValue (expression , null );
355+ }
356+ if (expression instanceof J .NewClass ||
357+ expression instanceof J .NewArray ||
358+ expression instanceof J .Lambda ||
359+ expression instanceof J .MemberReference ) {
360+ return true ;
361+ }
362+ JavaType type = expression .getType ();
363+ return type == JavaType .Primitive .Boolean ||
364+ type == JavaType .Primitive .Byte ||
365+ type == JavaType .Primitive .Char ||
366+ type == JavaType .Primitive .Double ||
367+ type == JavaType .Primitive .Float ||
368+ type == JavaType .Primitive .Int ||
369+ type == JavaType .Primitive .Long ||
370+ type == JavaType .Primitive .Short ;
371+ }
372+
348373 private boolean expressionReferences (Expression expr , String name ) {
349374 return new JavaIsoVisitor <AtomicBoolean >() {
350375 @ Override
0 commit comments