Does Java have a using statement?
Solution 1:
Java 7 introduced Automatic Resource Block Management which brings this feature to the Java platform. Prior versions of Java didn't have anything resembling using
.
As an example, you can use any variable implementing java.lang.AutoCloseable
in the following way:
try(ClassImplementingAutoCloseable obj = new ClassImplementingAutoCloseable())
{
...
}
Java's java.io.Closeable
interface, implemented by streams, automagically extends AutoCloseable
, so you can already use streams in a try
block the same way you would use them in a C# using
block. This is equivalent to C#'s using
.
As of version 5.0, Hibernate Sessions implement AutoCloseable
and can be auto-closed in ARM blocks. In previous versions of Hibernate Session did not implement AutoCloseable
. So you'll need to be on Hibernate >= 5.0 in order to use this feature.
Solution 2:
Before Java 7, there was no such feature in Java (for Java 7 and up see Asaph's answer regarding ARM).
You needed to do it manually and it was a pain:
AwesomeClass hooray = null;
try {
hooray = new AwesomeClass();
// Great code
} finally {
if (hooray!=null) {
hooray.close();
}
}
And that's just the code when neither // Great code
nor hooray.close()
can throw any exceptions.
If you really only want to limit the scope of a variable, then a simple code block does the job:
{
AwesomeClass hooray = new AwesomeClass();
// Great code
}
But that's probably not what you meant.