Skip to content

Commit 8ecb139

Browse files
committed
add post
1 parent 56b0fe6 commit 8ecb139

File tree

2 files changed

+46
-7
lines changed

2 files changed

+46
-7
lines changed

source/_posts/.idea/workspace.xml

Lines changed: 0 additions & 7 deletions
This file was deleted.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
title: Java14新特性:增强 instanceOf 类型推断
2+
tags:
3+
- java14
4+
categories:
5+
- Dev
6+
- Java
7+
date: 2020-03-20 08:17:00
8+
cover: true
9+
10+
---
11+
12+
![](http://q6pznk9ej.bkt.clouddn.com/java.jpg)
13+
<!-- more -->
14+
>Java中instanceof是用来判断对象的类型是否是目标类型。如果是返回true,不是返回false。
15+
16+
在Java 14之前,示例如下:
17+
```
18+
if (obj instanceof String) {
19+
String str = (String) obj;
20+
str.contains("A") ;
21+
}else{
22+
str = "";
23+
}
24+
```
25+
obj instanceof String已经为true,在后面的代码里,我们还是要清晰的定义一个新变量,并且要做类型强转换。
26+
27+
Java 14对instanceof引入了模式匹配,修改后的代码如下:
28+
```
29+
if (!(obj instanceof String str)) {
30+
str.contains("A") ;
31+
} else {
32+
str = "";
33+
}
34+
```
35+
定义了str,就可以在后续代码使用,不在需要显式做类型转换了。
36+
37+
还能继续加入判断条件
38+
```
39+
if (obj instanceof String str && str.contains("A")) {
40+
System.out.println(str);
41+
}
42+
43+
if (obj instanceof String str || str.contains("A")) {
44+
System.out.println(str);
45+
}
46+
```

0 commit comments

Comments
 (0)