# Tuesday, 28 June 2011
« [deleted] | Main | How to Detect if a Method is Overridden ... »
java.lang.AutoCloseable

Java 7 introduces try-with-resources. This is similar1 to the C# using construct. Yesterday I committed the changes necessary for IKVM to have bi-directional interop between these two. Previously, every2 Java class that implemented java.io.Closeable already automatically got an System.IDisposable for free from ikvmc, but now the new java.lang.AutoCloseable interface shadows IDisposible (similar to how java.lang.Comparable shadows System.IComparable).

The fact that AutoCloseable shadows IDisposable means that it extends IDisposable (this is not visible from Java) and that all Java code that works with AutoCloseable will accept IDisposable references.

Unfortunately this is technically a breaking change. If you have a .NET class that implements java.io.Closeable, it now also must implement IDisposable, but since that makes sense, it's likely it already does.

Since java.io.Closeable now extends java.lang.AutoCloseable, the special casing of java.io.Closeable has been removed from ikvmc.

Here's an example of using the new Java 7 try-with-resources feature on a .NET type:

import cli.System.IO.*;

public class TryWithResources {
  public static void main(String[] args) {
    try (FileStream fs = File.OpenWrite("foo.txt")) {
      fs.Write("Foo".getBytes(), 0, 3);
    }
  }
}


1 There is one important difference in that try-with-resources supports something called suppressed exceptions.
2 Not every class. If you already implement IDisposable explicitly, you don't get an extra one.

Tuesday, 28 June 2011 07:44:14 (W. Europe Daylight Time, UTC+02:00)  #    Comments [0]
Name
E-mail
Home page

I apologize for the lameness of this, but the comment spam was driving me nuts. In order to be able to post a comment, you need to answer a simple question. Hopefully this question is easy enough not to annoy serious commenters, but hard enough to keep the spammers away.

Anti-Spam Question: What method on java.lang.System returns an object's original hashcode (i.e. the one that would be returned by java.lang.Object.hashCode() if it wasn't overridden)? (case is significant)

Answer:  
Comment (HTML not allowed)  

Live Comment Preview