Java 14: instanceof的模式匹配(预览)

之前的instanceof使用

在Java 14对instanceof进行了一些改动.这些改动目前是预览的(后期可能会有变化).

在Java 14之前,我们通常是这样使用instanceof的:


1
2
3
4
5
6
7
static void show(Object obj){
  User user=null;
  if(obj instanceof User){
    user=(User)obj;
    System.out.println(user.name());
  }
}

会发现在instanceof判断obj是User的实例之后,还需要进行一次强制转换并且还需要提前定义一个变量(user)接收强制转换后的结果,才能使用.显得多余且繁琐.这次的改进就是为了优化instanceof的使用而来.

java标志
image-3141

Java 14中对instanceof的改进(预览)

基本改进

先来一段代码:


1
2
3
4
5
static void show1(Object obj){
        if(obj instanceof User user){
            System.out.println(user.name());
        }
}

 

可以和上面对比一下改进,发现至少有两点改进:

  • 1. 不用提前定义局部变量user;
  • 2. 局部变量名可直接写在类型后面,也就是user,在判断为true时,可直接使用user.

模式变量的作用域

模式变量存在作用域限制: 它只能在if中使用,而不能在else if/else中使用.否则会提示编译错误.

如下:


1
2
3
4
5
6
7
8
9
static void show1(Object obj){
    if(obj instanceof User user){
        System.out.println(user.name());
    }else if(obj instanceof String){
        // System.out.println(user.name()); error
    }else{
        // System.out.println(user.name()); error
    }
}

 

当然你可以这样用:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
    private static User user=new User("aa",12);
static void show1(Object obj){

    if(obj instanceof User user){
        // 调用instanceof模式匹配变量.
        System.out.println(user.name());
    }else if(obj instanceof String){
        // 调用的静态变量user.
        System.out.println(user.name());
    }else{
        // 调用的静态变量user.
        System.out.println(user.name());
    }
}

因此,记住只在if中使用instanceof模式变量.

instanceof模式变量简化if表达式

可以使用instanceof模式变量来简化if表达式:

先看原始的:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Person {
    String name;
    int age;

    @Override
    public boolean equals(Object o) {
        if (o instanceof Person) {
            Person other = (Person) o;
            if (name.equals(other.name) && age == other.age) {
                return true;
            }
        }
        return false;
    }
}

简化第一步,引入模式变量:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    public class Person {
        String name;
        int age;

        @Override
        public boolean equals(Object o) {
            /// 将局部变量other提入条件表达式.
            if (o instanceof Person other) {
                /// 移除此行. Person other = (Person) o;
                if (name.equals(other.name) && age == other.age) {
                    return true;
                }
            }
            return false;
        }
    }

第二步,将第二个if与第一个if合并:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Person {
        String name;
        int age;

        @Override
        public boolean equals(Object o) {
            /// 将局部变量other提入条件表达式.
            if (o instanceof Person other && name.equals(other.name) && age == other.age) {
                /// 移除此行. Person other = (Person) o;
                /// 与上层if合并. if (name.equals(other.name) && age == other.age) {
                    return true;
                /// 与上层if合并 }
            }
            return false;
        }
    }

第三步,终极优化,直接返回if中的条件判断:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Person {
        String name;
        int age;

        @Override
        public boolean equals(Object o) {
            return o instanceof Person other && name.equals(other.name) && age == other.age;
            /// 将局部变量other提入条件表达式.
            /// if (o instanceof Person other && name.equals(other.name) && age == other.age) {
                /// 移除此行. Person other = (Person) o;
                /// 与上层if合并. if (name.equals(other.name) && age == other.age) {
                /// return true;
                /// 与上层if合并 }
            /// }
            /// return false;
        }
}

仅需一行,就可以直接返回equals的结果.

完整代码

完整代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

record User(String name, int age) implements Serializable {
}

public class Main {



    public class Person {
        String name;
        int age;

        @Override
        public boolean equals(Object o) {
            return o instanceof Person other && name.equals(other.name) && age == other.age;
            /// 将局部变量other提入条件表达式.
            /// if (o instanceof Person other && name.equals(other.name) && age == other.age) {
                /// 移除此行. Person other = (Person) o;
                /// 与上层if合并. if (name.equals(other.name) && age == other.age) {
                /// return true;
                /// 与上层if合并 }
            /// }
            /// return false;
        }
    }



    static void show(Object obj){
        User user=null;
        if(obj instanceof User){
            user=(User)obj;
            System.out.println(user.name());
        }
    }

    private static User user=new User("aa",12);
    static void show1(Object obj){
        if(obj instanceof User user){
            System.out.println(user.name());
        }else if(obj instanceof String){
            System.out.println(user.name());
        }else{
            System.out.println(user.name());
        }
    }

    public static void main(String[] args) {
        var user = new User("测试用户", 20);
        show1(user);
        show1("str");
        show1(new StringBuffer("StringBuffer"));
    }
}

Java 14:Switch表达式

Java 14相关

java标志
image-3128

成为标准功能

温馨提示: 目前仅IDEA 2020.1 EAP及以上版本支持Java 14中所有新增功能.因此请使用最新版本(目前链接到2020.1 EAP版本,发布正式版之后,可在稳定版中下载.)!~

Switch表达式是Java 12加入的,在Java 13成为预览版,在Java 14成为标准版.也就是正式功能.

同时,Switch表达式在Java 14中并未增加任何新特性.因此关于Switch的变更历史.可以参考: Java 13: Switch表达式Java 12预览:Switch表达式.