Pattern matching instanceof [closed]

半腔热情 提交于 2020-05-23 06:50:07

问题


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);
}

I am using Java 14.


回答1:


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

And now you can do:

java MainClass --enable-preview

Example of 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);
}

Another example copied from JEP:

if (obj instanceof String s && s.length() > 5) {.. s.contains(..) ..}


来源:https://stackoverflow.com/questions/61939967/pattern-matching-instanceof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!