理解JDK 7 - try-with-resources

4

我是一名 .net 开发人员。最近,我对比较 Java 和 C# 产生了兴趣。我发现 Java 的 try-with-resources 相当于 C# 的 using 块。但是,我并不能完全理解它。我知道 C# 的 using 块是一种语言特性,编译器会为其生成代码。我想更深入地了解 try-with-resources,并有一些问题:

  1. Is it a langauge feature similar to C#'s using block?

  2. What is the equivalent JDK 6 code for the following:

    try(SomeResource resource = new SomeResource())
    {
        //Some logic
    }
    
  3. What is the equivalent JDK 6 code for the following:

    try(SomeResource resource = new SomeResource())
    {
        //Some logic
    }
    catch(SomeException ex)
    {
    }
    
  4. What is Java equivalent of C#'s Reflector or ILSpy tool? i.e. tool to disassemble Java byte code class files and view Java code of it.

1个回答

7
  1. 是的,它们非常相似。
  2. 等价的Java代码是完全相同的
  3. 等价的Java代码也是完全相同的
  4. 有几个Java反编译器,但我很喜欢JD-GUI

更新:我读错了你的问题。JDK6的代码如下:

try {
    final SomeResource resource = new SomeResource();
    Throwable resourceEx = null;
    try {
      //... use resource
    } catch (Throwable t) {
        resourceEx = t;
        throw t;
    } finally {

        if(resource != null) {
            if(resourceEx != null) {
                try {
                    resource.close();
                } catch (Throwable t) {
                    resourceEx.addSuppressed(t);
                }
            } else {
                resource.close();
            }
        }
    }
} catch (SomeException ex) {
//...standard error handling
}

关闭。资源的初始化由catch-SomeException块覆盖。此外,资源关闭逻辑发生在嵌套的try-finally块中,因此如果抛出SomeException,则在控制流到达catch-SomeException块之前关闭资源。请参见JLS 14.20.3.2以获取详细信息:http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.3.2 - Stuart Marks
@GaryF:在你的代码片段中,SomeResource的构造函数不应该在try块中被调用吗?也就是说,它不应该是:try { resource = new SomeResource() }.....吗? - Anand Patel
你们两个都是正确的。实际上,这需要更多的涉及。我已经更新了我的答案。 - GaryF
@GaryF:在你的代码片段中,gzip和gzipEx是什么,它们在哪里声明的? - Anand Patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接