Skip to content

Commit 9c36dc1

Browse files
ZzetTtimtebeek
andauthored
feat: Prevent migration of singletonMap with null value or null key (#772)
* feat: Prevent migration of singletonMap with null value or null key * Apply suggestions from code review * Update MigrateCollectionsSingletonMap.java * Update MigrateCollectionsSingletonMap.java * Update MigrateCollectionsSingletonMap.java --------- Co-authored-by: Tim te Beek <[email protected]> Co-authored-by: Tim te Beek <[email protected]>
1 parent 1de3801 commit 9c36dc1

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public String getDisplayName() {
4040

4141
@Override
4242
public String getDescription() {
43-
return "Prefer `Map.Of(..)` instead of using `Collections.singletonMap()` in Java 9 or higher.";
43+
return "Prefer `Map.of(..)` instead of using `Collections.singletonMap()` in Java 9 or higher.";
4444
}
4545

4646
@Override
@@ -49,7 +49,7 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
4949
@Override
5050
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
5151
J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
52-
if (SINGLETON_MAP.matches(method)) {
52+
if (SINGLETON_MAP.matches(method) && isNotLiteralNull(m)) {
5353
maybeRemoveImport("java.util.Collections");
5454
maybeAddImport("java.util.Map");
5555
StringJoiner mapOf = new StringJoiner(", ", "Map.of(", ")");
@@ -68,6 +68,11 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)
6868

6969
return m;
7070
}
71+
72+
private boolean isNotLiteralNull(J.MethodInvocation m) {
73+
return !(J.Literal.isLiteralValue(m.getArguments().get(0), null) ||
74+
J.Literal.isLiteralValue(m.getArguments().get(1), null));
75+
}
7176
});
7277
}
7378
}

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,25 @@ class Test {
8585
)
8686
);
8787
}
88+
89+
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/571")
90+
@Test
91+
void shouldNotConvertLiteralNull() {
92+
//language=java
93+
rewriteRun(
94+
version(
95+
java(
96+
"""
97+
import java.util.*;
98+
99+
class Test {
100+
Map<String, String> mapWithNullKey = Collections.singletonMap(null, "foo");
101+
Map<String, String> mapWithNullValue = Collections.singletonMap("bar", null);
102+
}
103+
"""
104+
),
105+
9
106+
)
107+
);
108+
}
88109
}

0 commit comments

Comments
 (0)