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

Posted Dreamer who

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于java9新特性-增强的try-with-resources块的主要内容,如果未能解决你的问题,请参考以下文章

Java9新特性之HTTP2和REPL

JAVA9新特性之模块化系统和jshell体验

JAVA8新特性——接口定义增强

jdk11新特性——官方的更新列表

jdk11新特性——官方的更新列表

Java9 进程API详细介绍