Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I replicate the functionality of C#'s 'using' statement in Java?

I'm converting some C# code to Java and it contains the using statement. How should I replicate this functionality in Java? I was going to use a try, catch, finally block but I thought I'd check with you guys first.

like image 648
James Avatar asked Dec 28 '22 11:12

James


1 Answers

That's correct. A C# using block is just syntactic sugar for that anyway. The closest Java equivalent to IDisposable is Closeable.

There is a proposal (which is partially committed already), called Automatic Resource Management, for adding similar functionality to Java 7. It would use try-finally behind the scenes, and proposes creating a new Disposable interface (which would be a superinterface of Closeable).

like image 109
Matthew Flaschen Avatar answered Jan 22 '23 15:01

Matthew Flaschen