Skip to content

Commit 062873e

Browse files
authored
Fix IfElseIfConstructToSwitch null safety regression (#1014)
* Fix IfElseIfConstructToSwitch null safety regression (issue #1013) When converting instanceof chains to switch without an explicit null check, emit `case null, default` instead of just `default` to preserve instanceof's null-safe behavior. Previously, the recipe would generate code that throws NPE when the switched variable is null, unlike the original if-else chain. * Fix UpgradeToJava21Test expectation for case null, default
1 parent 7948b9a commit 062873e

3 files changed

Lines changed: 5 additions & 5 deletions

File tree

src/main/java/org/openrewrite/java/migrate/lang/IfElseIfConstructToSwitch.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ public J.Return visitReturn(J.Return return_, AtomicBoolean atomicBoolean) {
212212
arguments[i++] = getPattern(instanceOf);
213213
arguments[i++] = getStatement(entry.getValue());
214214
}
215-
switchBody.append("default -> #{any()};\n");
215+
switchBody.append(nullCheckedParameter != null ? "default" : "case null, default").append(" -> #{any()};\n");
216216
if (else_ != null) {
217217
arguments[i] = getStatement(else_);
218218
} else {

src/test/java/org/openrewrite/java/migrate/UpgradeToJava21Test.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ private static double convertToDouble(Object value) {
6161
case String string -> Double.parseDouble(string);
6262
case Integer integer -> integer.doubleValue();
6363
case Long long1 -> long1.doubleValue();
64-
default -> (double) value;
64+
case null, default -> (double) value;
6565
};
6666
}
6767
}

src/test/java/org/openrewrite/java/migrate/lang/IfElseIfConstructToSwitchTest.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ static String formatter(Object obj) {
128128
String str = "String";
129129
formatted = String.format("%s %s", str, s);
130130
}
131-
default -> formatted = "unknown";
131+
case null, default -> formatted = "unknown";
132132
}
133133
return formatted;
134134
}
@@ -331,7 +331,7 @@ static String formatter(Object obj) {
331331
String str = "String";
332332
formatted = String.format("%s %s", str, s);
333333
}
334-
default -> formatted = "unknown";
334+
case null, default -> formatted = "unknown";
335335
}
336336
return formatted;
337337
}
@@ -436,7 +436,7 @@ static String describe(Object obj) {
436436
case Dog d -> result = "dog";
437437
case Cat c -> result = "cat";
438438
case Bird b -> result = "bird";
439-
default -> result = "unknown";
439+
case null, default -> result = "unknown";
440440
}
441441
return result;
442442
}

0 commit comments

Comments
 (0)