Skip to content

Commit 972a519

Browse files
authored
Skip UseMapOf when put() argument is a null literal (#1094)
`Map.of(..)` throws `NullPointerException` on null keys or values, so converting a `HashMap` containing null arguments is not behavior-preserving. Fixes #1092
1 parent 9b419e9 commit 972a519

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

src/main/java/org/openrewrite/java/migrate/util/UseMapOf.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@ public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) {
6868
return n;
6969
}
7070
J.MethodInvocation put = (J.MethodInvocation) stat;
71+
for (Expression arg : put.getArguments()) {
72+
if (J.Literal.isLiteralValue(arg, null)) {
73+
return n;
74+
}
75+
}
7176
args.addAll(put.getArguments());
7277
if (useEntries) {
7378
template.add("Map.entry(#{any()}, #{any()})");

src/test/java/org/openrewrite/java/migrate/util/UseMapOfTest.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,48 @@ Map<String, Integer> values() {
163163
);
164164
}
165165

166+
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/1092")
167+
@Test
168+
void doNotChangeWhenNullValue() {
169+
//language=java
170+
rewriteRun(
171+
java(
172+
"""
173+
import java.util.HashMap;
174+
import java.util.Map;
175+
176+
class Test {
177+
Map<String, String> m = new HashMap<>() {{
178+
put("key", "value");
179+
put("nullable", null);
180+
}};
181+
}
182+
"""
183+
)
184+
);
185+
}
186+
187+
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/1092")
188+
@Test
189+
void doNotChangeWhenNullKey() {
190+
//language=java
191+
rewriteRun(
192+
java(
193+
"""
194+
import java.util.HashMap;
195+
import java.util.Map;
196+
197+
class Test {
198+
Map<String, String> m = new HashMap<>() {{
199+
put(null, "value");
200+
put("key", "other");
201+
}};
202+
}
203+
"""
204+
)
205+
);
206+
}
207+
166208
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/566")
167209
@Test
168210
void changeDoubleBraceInitForNonStringTypes() {

0 commit comments

Comments
 (0)