- Java 14 Tutorial
- Java 14 - Home
- Java 14 - Overview
- Java 14 - Environment Setup
- Java 14 Language Changes
- Java 14 - Switch Expressions
- Java 14 - Text Blocks
- Java 14 - pattern for instanceOf
- Java 14 - NullPointerException
- Java 14 JVM Changes
- Java 14 - Packaging Tools
- Java 14 - NUMA Aware G1
- Java 14 - Others
- Java 14 - Deprecation & Removals
- Java 14 Useful Resources
- Java 14 - Quick Guide
- Java 14 - Useful Resources
- Java 14 - Discussion
Java 14 - instanceof 中的模式匹配
Java 14 引入了instanceof 运算符来拥有类型测试模式作为预览功能。类型测试模式有一个谓词来指定具有单个绑定变量的类型。
句法
if (obj instanceof String s) { }
例子
考虑以下示例 -
ApiTester.java
public class APITester { public static void main(String[] args) { String message = "Welcome to Tutorialspoint"; Object obj = message; // Old way of getting length if(obj instanceof String){ String value = (String)obj; System.out.println(value.length()); } // New way of getting length if(obj instanceof String value){ System.out.println(value.length()); } } }
编译并运行程序
$javac -Xlint:preview --enable-preview -source 14 APITester.java $java --enable-preview APITester
输出
25 25