Java 7 - 尝试/最后:它如何知道在第三方API中调用清理资源的方法是什么?

时间:2013-08-26 23:03:53

标签: java

在Java 7中,而不是

        try {
              fos = new FileOutputStream("movies.txt");
              dos = new DataOutputStream(fos);
              dos.writeUTF("Java 7 Block Buster");
        } catch (IOException e) {
              e.printStackTrace();
        } finally {

              try {
                    fos.close();
                    dos.close();

              } catch (IOException e) {
                    // log the exception
              }
        }

你可以这样做

        try (FileOutputStream fos = new FileOutputStream("movies.txt");
              DataOutputStream dos = new DataOutputStream(fos)) {
              dos.writeUTF("Java 7 Block Buster");
        } catch (IOException e) {
              // log the exception
        }

但我正在使用第三方API,此API要求调用.close()来清理开放资源

try (org.pdfclown.files.File file = new org.pdfclown.files.File("movies.pdf")) {
         ...
}

Java 7如何知道如何处理这样的第三方API?它将如何知道要调用哪种方法?

3 个答案:

答案 0 :(得分:10)

Java 7引入了"try-with-resources"。括号中的参数必须实现AutoCloseable接口,该接口定义close方法。

我猜测org.pdfclown.files.File类实现了AutoCloseable接口。

修改

Closeable确实实现的org.pdfclown.files.File接口在Java 7中扩展AutoCloseable。所以它应该在Java 7中工作,因为org.pdfclown.files.File确实实现了AutoCloseable即使它间接地这样做了。

答案 1 :(得分:6)

如果您的第三方类实现了AutoClosable接口

,它将会运行良好

我已查看pdfclown来源herehere,但似乎没有实施AutoClosable

以下是File.java来源的重要部分:

public final class File
  implements Closeable

,如其他答案和评论中所述,Closable延伸AutoClosable

答案 2 :(得分:3)

在java 7中,编译器知道任何实现AutoCloseable的类并且被声明为try-with-resources语句的一部分,以调用close方法作为finally块的一部分。