本文詳細介紹了自 JDK 7 引入的 try-with-resources 語句的原理和用法,以及介紹了 JDK 9 對 try-with-resources 的改進,使得用戶可以更加方便、簡潔的使用 try-with-resources 語句。,需要的朋友可以參考下
在 JDK 7 之前,資源需要手動關閉
例如下面一個很常見的文件操作的例子:
Charset charset = Charset.forName("US-ASCII"); String s = ...; BufferedWriter writer = null; try { writer = Files.newBufferedWriter(file, charset); writer.write(s, 0, s.length()); } catch (IOException x) { System.err.format("IOException: %s%n", x); } finally { if (writer != null) writer.close(); }
在 JDK 7 之前,你一定要牢記在 finally 中執行 close 以釋放資源
JDK 7 中的 try-with-resources 介紹
try-with-resources 是 JDK 7 中一個新的異常處理機制,它能夠很容易地關閉在 try-catch 語句塊中使用的資源。所謂的資源(resource)是指在程序完成後,必須關閉的對象。try-with-resources 語句確保了每個資源在語句結束時關閉。所有實現了 java.lang.AutoCloseable 接口(其中,它包括實現了 java.io.Closeable 的所有對象),可以使用作爲資源。
例如,我們自定義一個資源類
public class Demo { public static void main(String[] args) { try(Resource res = new Resource()) { res.doSome(); } catch(Exception ex) { ex.printStackTrace(); } } } class Resource implements AutoCloseable { void doSome() { System.out.println("do something"); } @Override public void close() throws Exception { System.out.println("resource is closed"); } }
執行輸出如下:
do something resource is closed
可以看到,資源終止被自動關閉了。
再來看一個例子,是同時關閉多個資源的情況:
public class Main2 { public static void main(String[] args) { try(ResourceSome some = new ResourceSome(); ResourceOther other = new ResourceOther()) { some.doSome(); other.doOther(); } catch(Exception ex) { ex.printStackTrace(); } } } class ResourceSome implements AutoCloseable { void doSome() { System.out.println("do something"); } @Override public void close() throws Exception { System.out.println("some resource is closed"); } } class ResourceOther implements AutoCloseable { void doOther() { System.out.println("do other things"); } @Override public void close() throws Exception { System.out.println("other resource is closed"); } }
最終輸出爲:
do something do other things other resource is closed some resource is closed
在 try 語句中越是最後使用的資源,越是最早被關閉。
try-with-resources 在 JDK 9 中的改進
作爲 Milling Project Coin 的一部分, try-with-resources 聲明在 JDK 9 已得到改進。如果你已經有一個資源是 final 或等效於 final 變量,您可以在 try-with-resources 語句中使用該變量,而無需在 try-with-resources 語句中聲明一個新變量。
例如,給定資源的聲明
// A final resource final Resource resource1 = new Resource("resource1"); // An effectively final resource Resource resource2 = new Resource("resource2");
老方法編寫代碼來管理這些資源是類似的:
// Original try-with-resources statement from JDK 7 or 8 try (Resource r1 = resource1; Resource r2 = resource2) { // Use of resource1 and resource 2 through r1 and r2. }
而新方法可以是
// New and improved try-with-resources statement in JDK 9 try (resource1; resource2) { // Use of resource1 and resource 2. }
看上去簡潔很多吧。對 Java 未來的發展信心滿滿。
願意嘗試 JDK 9 這種新語言特性的可以下載使用 JDK 9 快照。Enjoy!
源碼
本章例子的源碼,可以在 https://github.com/waylau/essential-java 中 com.waylau.essentialjava.exception.trywithresources 包下找到。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。