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.