试用转让所有权

时间:2014-05-30 21:44:47

标签: java exception-handling try-with-resources

在Java 7中,有一种try-with语法,可以确保在所有代码路径中关闭像InputStream这样的对象,而不管异常如何。但是,在try-with块中声明的变量("是")是最终的。

try (InputStream is = new FileInputStream("1.txt")) {
    // do some stuff with "is"
    is.read();

    // give "is" to another owner
    someObject.setStream(is);

    // release "is" from ownership: doesn't work because it is final
    is = null;
}

是否有简洁的语法在Java中表达这一点?考虑这种异常不安全的方法。添加相关的try / catch / finally块会使方法更加冗长。

InputStream openTwoFiles(String first, String second)
{
    InputStream is1 = new FileInputStream("1.txt");

    // is1 is leaked on exception
    InputStream is2 = new FileInputStream("2.txt");

    // can't use try-with because it would close is1 and is2
    InputStream dual = new DualInputStream(is1, is2);
    return dual;
}

显然,我可以让调用者打开这两个文件,将它们放在try-with块中。这只是我想在将资产的所有权转移给另一个对象之前对资源执行某些操作的情况的一个例子。

1 个答案:

答案 0 :(得分:1)

try-with旨在用于所识别的资源必须永远不会超出try块范围的情况。

如果要使用try-with构造,则必须按如下方式更改设计:

  1. 删除openTwoFiles()方法。它没有价值。
  2. DualInputStream类创建一个带有两个文件名的构造函数,并创建两个InputStreams。声明此构造函数抛出IOException并允许它抛出IOExceptions
  3. 在try-with构造中使用新构造函数。