【JAVA语法糖】try-with-resources

2020-04-21  本文已影响0人  Hao_38b9

语法糖之——try-with-resources

使用方法

try(FileInputStream inputStream = new FileInputStream("README.md")){
    inputStream.read();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

以上代码可以转化为

try(FileInputStream inputStream = new FileInputStream("README.md")){
    inputStream.read();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}finally{
    if(inputstream!=null){
        inputstream.close();
    }
}

优点

自定义类使用try-with-resources

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Test implements AutoCloseable{
    public void send(){
        System.out.println("发送");
    }
    @Override
    public void close() throws Exception {
        System.out.println("对象关闭了");
    }

    public static void main(String[] args) {
        try(Test test = new Test()){
            test.send();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读