java9新特性-增强的try-with-resources块

java7新增了自动关闭资源的特性,碰到异常的时候,我们不必再写一堆啰嗦的处理代码,而是简洁的如下:

 try (ServerSocket socket = new ServerSocket(8090)) {
            System.out.println(socket);
        }

或者多个资源的情况下:

 try (ServerSocket socket = new ServerSocket(8090);
             ServerSocket socket2 = new ServerSocket(8020)) {
            System.out.println(socket);
            System.out.println(socket2);
        }

多个资源自动调用close()方法的顺序与声明资源的顺序是相反的。

但是资源变量的声明必须在try catch块中,如果不在,会出现错误提示:

 public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(8090);
        ServerSocket socket2 = new ServerSocket(8020);

        try (socket; socket2) {
            System.out.println(socket);
            System.out.println(socket2);
        }
    }

IDE也会提示:

那么我们只能重新再try catch块中声明变量方式解决:

try (ServerSocket temp = socket; ServerSocket temp2 = socket2) {
            System.out.println(socket);
            System.out.println(socket2);
        }

不过,java9打破这种限制:

 public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(8090);
        ServerSocket socket2 = new ServerSocket(8020);

        try (socket; socket2; ServerSocket socket3 = new ServerSocket(9090)) {
            System.out.println(socket);
            System.out.println(socket2);
            System.out.println(socket3);
        }
    }

而且变量不用声明为final,默认属于final变量。

完整的示例代码:

/**
 * @author sdcuike
 * @date 2019/10/19
 */
public class TypeInference {
    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(8090);
        ServerSocket socket2 = new ServerSocket(8020);
        try (socket; socket2; ServerSocket socket3 = new ServerSocket(9030)) {
            System.out.println(socket.toString() + socket.isClosed());
            System.out.println(socket2.toString() + socket2.isClosed());
            System.out.println(socket3.toString() + socket3.isClosed());
        }

        print(socket);
        ServerSocket socket4 = new ServerSocket(8020);
        print(socket4);
        print(socket4);
    }

    private static void print(ServerSocket socket) throws IOException {
        try (socket) {
            System.out.println(socket.toString() + socket.isClosed());
        }
    }
}

结果:


ServerSocket[addr=0.0.0.0/0.0.0.0,localport=8090]false
ServerSocket[addr=0.0.0.0/0.0.0.0,localport=8020]false
ServerSocket[addr=0.0.0.0/0.0.0.0,localport=9030]false
ServerSocket[addr=0.0.0.0/0.0.0.0,localport=8090]true
ServerSocket[addr=0.0.0.0/0.0.0.0,localport=8020]false
ServerSocket[addr=0.0.0.0/0.0.0.0,localport=8020]true

Process finished with exit code 0

发布了296 篇原创文章 · 获赞 178 · 访问量 124万+

猜你喜欢

转载自blog.csdn.net/doctor_who2004/article/details/102674540