java.lang.AutoCloseable

來源:互聯網
上載者:User

標籤:detail   china   led   exce   str   dna   flush   closeable   參考   

java.lang.AutoCloseable和java.io.Closeable
public interface AutoCloseable {    void close() throws Exception;}public interface Closeable extends AutoCloseable {    public void close() throws IOException;}
  • java.lang.AutoCloseable是JDK7添加的新介面
  • AutoCloseable介面對try-with-resource提供支援
  • java.io.Closeable是JDK5添加的介面。從JDK7開始,Closeable擴充了AutoCloseable。因此,在JDK7中,所有實現了Closeable介面的類也都實現了AutoCloseable介面。
  • AutoCloseable 是一個更高抽象層次的介面,不一定用在 IO 上,所以它裡面的 close 方法拋出的異常是 Exception,而非 IOException。
  • Closable 只用作 IO 流上,所以 close 方法拋出的異常是 IOException。
自訂AutoClosable 實現
public class TryWithResource implements AutoCloseable {    @Override    public void close() throws Exception {        StackTraceElement stack[] = Thread.currentThread().getStackTrace();        for (StackTraceElement ste : stack) {            System.out                    .println("called by " + ste.getClassName() + "." + ste.getMethodName() + " / " + ste.getFileName());        }    }    public static void main(String[] args) {        try (TryWithResource twr = new TryWithResource()) {            System.out.println("use end...");            throw new Exception("xxx");        } catch (Exception e) {            System.out.println("close error...");        }    }}
參考資料
  • 探究java IO之AutoCloseable,Closeable和Flushable介面
  • AutoCloseable & Closable

java.lang.AutoCloseable

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.