instanceof模式匹配从jdk14第一次预览,jdk15第二次预览,到jdk16变为正式版,将之前的书写方式变得更简洁直观,使代码不再那么繁琐;
之前的instanceof要这麽写:
@Test
void test() {
Object o = "a";
if (o instanceof Integer) {
Integer i = (Integer) o;
System.out.println("数字:" + i);
} else if (o instanceof String) {
String s = (String) o;
System.out.println("字符串:" + s);
}
}
先要在if里判断类型,然后在代码块里进行强制转换成新变量,才能继续使用对应类型的变量进行操作;
在jdk16中可以这样写了:
@Test
void test() {
Object o = "a";
if (o instanceof Integer i) {
System.out.println("数字:" + i);
} else if (o instanceof String s) {
System.out.println("字符串:" + s);
}
}
将类型判断和强制转换合并到一个instanceof操作里,代码写起来更简洁直观;
另外,instanceof的新变量作用域只在if语句里;
instanceof操作后面的&&与操作里也可以继续使用instanceof的变量,不过由于短路操作,后面的||或操作不能使用instanceof的变量,因为有可能instanceof不满足新变量未定义;
可以这样写:
@Test
void test() {
Object o = "a";
if (o instanceof Integer i) {
System.out.println("数字:" + i);
} else if (o instanceof String s && s.equals("b")) {
System.out.println("字符串b:" + s);
}
}
但是不能这样写: