Language 高级

模式匹配现在适用于原始类型,不仅限于对象。

✕ Java 8
String classify(int code) {
    if (code >= 200 && code < 300)
        return "success";
    else if (code >= 400 && code < 500)
        return "client error";
    else
        return "other";
}
✓ Java 25 (Preview)
String classify(int code) {
    return switch (code) {
        case int c when c >= 200
            && c < 300 -> "success";
        case int c when c >= 400
            && c < 500 -> "client error";
        default -> "other";
    };
}
发现此代码有问题? 告诉我们。
📦

无装箱

直接匹配原始类型——无需 Integer 包装器。

🎯

模式一致性

对象和原始类型使用相同的模式语法。

更好的性能

避免模式匹配中的自动装箱开销。

旧方式
手动范围检查
现代方式
原始类型模式
自 JDK
25
难度
高级
模式中的原始类型
预览

JDK 25 预览版(第三次预览,JEP 507)。需要 --enable-preview。

Java 25 将模式匹配扩展到原始类型。您可以在 instanceof 和 switch 中使用 int、long、double 等作为模式变量。

分享 𝕏 🦋 in