How can I replicate the functionality of a C # 'using' statement in Java?

I am converting C # code to Java and contains a using statement. How do I repeat this function in Java? I was going to use the try , catch , finally catch , but I thought I would check with you guys first.

+4
source share
3 answers

The standard idiom for resource handling in Java:

 final Resource resource = acquire(); try { use(resource); } finally { resource.dispose(); } 

Common errors include trying to use the same try with the exception of catch and subsequent use, which creates a mess using null , etc.

Execute Around Idiom can extract such constructs, although the Java syntax is verbose.

 executeWith(new Handler() { public void use(Resource resource) { ... }}); 
+2
source

It is right. A C # block using a block is just syntactic sugar for this. The closest Java equivalent to IDisposable is Closeable .

There is a proposal (which has already been partially implemented), called Automatic Resource Management , to add similar functionality in Java 7. This uses try-finally behind the scenes and suggests creating a new one-time interface (which would be the Closeable superinterface).

+8
source

Do not forget about zero verification! I.e

 using(Reader r = new FileReader("c:\test")){ //some code here } 

should translate to something like

 Reader r = null; try{ //some code here } finally{ if(r != null){ r.close() } } 

And also the closest () in java throw exceptions, so check out DbUtils.closeQuietly if you want your code to be larger than C #, e.g.

0
source

Source: https://habr.com/ru/post/1314744/


All Articles