Java7-Try/finally:它如何知道在第三方API中调用什么方法来清理资源?

Java7-Try/finally:它如何知道在第三方API中调用什么方法来清理资源?,java,Java,在Java7中,而不是 try { fos = new FileOutputStream("movies.txt"); dos = new DataOutputStream(fos); dos.writeUTF("Java 7 Block Buster"); } catch (IOException e) { e.printStackTrace();

在Java7中,而不是

        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")) {
         ...
}

Java7如何知道如何处理这样的第三方API?它如何知道调用什么方法?

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

java 7介绍。括号中的参数必须实现接口,接口定义
close
方法

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

编辑


该接口确实实现了Java 7中的
AutoCloseable
。所以它应该在Java7中工作,因为
org.pdfclown.files.File
确实实现了
AutoCloseable
,即使它是间接实现的。

如果您的第三方类实现了接口,它将很好地工作

我已经签出了
pdfclown
源代码,但它似乎没有实现
AutoClosable

以下是
File.java
源代码中的重要部分:

public final class File
  implements Closeable

但是,如其他答案和评论中所述,扩展了

你太接近了
org.pdfclown.files.File
实现了
java.io.Closable
,它(在java 7中)扩展了
java.lang.AutoCloseable
@Aleks DanielJakimenko它确实扩展了
AutoCloseable