简体   繁体   English

Java 7 Try-With-Resources(AutoCloseable)实现

[英]Java 7 Try-With-Resources (AutoCloseable) Implementation

My question is more of Why type than How . 我的问题更多的是为什么类型而不是如何

I know that in Java 7 the following works: 我知道在Java 7中有以下工作:

    try (
            FileInputStream in = new FileInputStream(source);
            FileOutputStream out = new FileOutputStream(target);
    ) {
        .....................
      } catch (......) {
       ...............
      }

And the following gives a syntax error: 以下是语法错误:

    FileInputStream in;
    FileOutputStream out;
    try (
            in = new FileInputStream(source);
            out = new FileOutputStream(target);
    ) {
        .....................
      } catch (......) {
       ...............
      }

I'm curious why is it so important for Closable / Autoclosable references to be local to the try block? 我很好奇,为什么它如此重要, Closable / Autoclosable引用是本地try块? Is it just the logic that if we didn't own it than it's dangerous to close ? 如果我们不拥有它而不是关闭它是危险的,这只是逻辑吗?

I don't have a reference for this language design decision, but I think the issue is that allowing non-local variables to be autoclosed would be dangerous—that is, it would allow many unsafe coding styles. 我没有这个语言设计决策的参考,但我认为问题是允许非局部变量自动闭合将是危险的 - 也就是说,它将允许许多不安全的编码样式。 From the Java Language Specification : Java语言规范

A resource declared in a ResourceSpecification is implicitly declared final (§4.12.4) if it is not explicitly declared final. 如果未明确声明为final,则在ResourceSpecification中声明的资源将被隐式声明为final(第4.12.4节)。

If the resources were not final , then inside the try block they might be reassigned, resulting in resource leaks. 如果资源不是final ,那么在try块中可能会重新分配它们,从而导致资源泄漏。 Since they are (implicitly or explicitly) final , the compiler would have to do a lot of extra work to ensure that the variables were definitely unassigned at the point the try resource specification was entered. 由于它们(隐式或显式)是final ,因此编译器必须做很多额外的工作以确保在输入try资源规范时肯定未分配变量。 It would probably also require changes to the compiler semantics of final , since the variables really should not have a valid value after the try block exits; 它可能还需要更改final的编译器语义,因为在try块退出后变量确实不应该有一个有效值; certainly not the value assigned to them in the try resource specification. 当然不是try资源规范中赋给它们的值。 The cleanest (perhaps only) thing to do is to make the variables go out of scope when the try block exits. 最干净(也许唯一)要做的是在try块退出时使变量超出范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM