我在 https://www.baeldung.com/java-pattern-matching-instanceof 上遇到了这个令人惊奇的主题。但是当我尝试运行以下代码时,它会抛出编译时错误:
if(obj instanceof String s) {
System.out.println(s);
}
错误提示:
语言级别“14”不支持“instanceof”中的模式
错误:(36, 34) java:instanceof 中的模式匹配是预览功能,默认情况下处于禁用状态。 (使用--enable-preview在instanceof中启用模式匹配)
但是我安装了 Java 14。
这是 Java 14 中的预览功能,请参阅 JEP 305 和 JEP 375。要启用此功能,请使用以下命令编译您的类:
javac MainClass.java --enable-preview --release 14
现在你可以做:
java MainClass --enable-preview
instanceof
的示例:
Object o = "Hello World!";
if (o instanceof String s) {
// no explicit type casting
s = s.replaceFirst("World", "Java"); // No compile time issues
System.out.println(s);
}
从 JEP 复制的另一个示例:
if (obj instanceof String s && s.length() > 5) {.. s.contains(..) ..}
自 Java 16 以来,“instanceof的模式匹配”是一个完全确定的功能(即不再是预览)。因此,当使用 Java 16 或更高版本时,无需单独启用此功能,因为它将开箱即用。
详情请参阅JEP-394。