What is the equivalent of 'defer' for Java?

This is just a short example of Go code:

package main import "fmt" func main() { defer fmt.Println("world") //use of keyword 'defer' fmt.Println("hello") } 

I find the equivalent of 'defer' in Java.

Instead of defer, I can use

 try { //do something } finally { //code using defer } 

Is there an alternative without using try / catch / finally?

+5
source share
2 answers

Java 7 has a try-with-resources statement .

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program terminates. The try-with-resources statement ensures that every resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects that implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from a file. BufferedReader is a resource that should be closed after the program is completed is:

 static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } } 

In this example, the resource declared in the try-with-resources statement is the BufferedReader. An expression about the declaration in brackets appears immediately after the try keyword. The BufferedReader class, in Java SE 7 and later, implements the java.lang.AutoCloseable interface. Because the BufferedReader instance is declared in the try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the BufferedReader.readLine method throwing an IOException).

+3
source

In java 7 and above, you can use try-with-resource:

 public static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } } 

when you exit try, it will close the docs resource: link

+3
source

All Articles