模式匹配实例 [英] Pattern matching instanceof
问题描述
我在 https://www.baeldung.com/上遇到了这个惊人的话题java-pattern-matching-instanceof.但是当我尝试运行以下代码时,它会引发编译时错误:
I came across this amazing topic on https://www.baeldung.com/java-pattern-matching-instanceof. But when I try to run the following code, it throws compile time error:
if(obj instanceof String s) {
System.out.println(s);
}
错误说:
语言级别14"不支持instanceof"中的模式
Patterns in 'instanceof' are not supported at language level '14'
Error:(36, 34) java: instanceof 中的模式匹配是一个预览功能,默认情况下是禁用的.(使用 --enable-preview 在 instanceof 中启用模式匹配)
Error:(36, 34) java: pattern matching in instanceof is a preview feature and is disabled by default. (use --enable-preview to enable pattern matching in instanceof)
但我安装了 Java 14.
But I have Java 14 installed.
推荐答案
这是 Java 14 中的预览功能,请参阅 JEP 305 和 JEP 375.要启用此功能,请使用以下命令编译您的类:
This is a preview feature in Java 14, see JEP 305 and JEP 375. To enable this, compile your class with:
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 复制的另一个示例:
Another example copied from JEP:
if (obj instanceof String s && s.length() > 5) {.. s.contains(..) ..}
这篇关于模式匹配实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!