Does Java have a using statement?
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.
Since Java 7 it does: http://blogs.oracle.com/darcy/entry/project_coin_updated_arm_spec
The syntax for the code in the question would be:
try (Session session = new Session())
{
// do stuff
}
Note that Session
needs to implement AutoClosable
or one of its (many) sub-interfaces.
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.
Technically:
DisposableObject d = null;
try {
d = new DisposableObject();
}
finally {
if (d != null) {
d.Dispose();
}
}