1 java pattern-matching preview-feature java-14
我在https://www.baeldung.com/java-pattern-matching-instanceof上遇到了这个惊人的话题。但是当我尝试运行以下代码时,它会引发编译时错误:
if(obj instanceof String s) {
System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)
错误说:
语言级别“14”不支持“instanceof”中的模式
Error:(36, 34) java: instanceof 中的模式匹配是一个预览功能,默认情况下是禁用的。(使用 --enable-preview 在 instanceof 中启用模式匹配)
但是我安装了 Java 14。
Ani*_*wat 11
这是 Java 14 中的预览功能,请参阅JEP 305和JEP 375。要启用此功能,请使用以下命令编译您的类:
javac MainClass.java --enable-preview --release 14
Run Code Online (Sandbox Code Playgroud)
现在你可以这样做:
java MainClass --enable-preview
Run Code Online (Sandbox Code Playgroud)
示例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);
}
Run Code Online (Sandbox Code Playgroud)
从 JEP 复制的另一个示例:
if (obj instanceof String s && s.length() > 5) {.. s.contains(..) ..}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
560 次 |
| 最近记录: |