10

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 am finding an equivalent of 'defer' in Java.

Instead of 'defer' I can use

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

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

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
Romeo
  • 115
  • 2
  • 11

3 Answers3

12

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 is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which 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 the file. BufferedReader is a resource that must be closed after the program is finished with it:

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 a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
IamNaN
  • 6,654
  • 5
  • 31
  • 47
4

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 the try it will close the resource docs: link

igreenfield
  • 1,618
  • 19
  • 36
0

You could also do something like this with some extra libraries. Unfortunately, there is the IOException to deal with.

import com.google.common.io.Closer;
import lombok.Cleanup;
import lombok.SneakyThrows;
import java.io.IOException;

public class Main {

    @SneakyThrows(IOException.class)
    public static void main(String[] args) {
        @Cleanup Closer defer = Closer.create();
        defer.register(() -> System.out.println("world"));
        System.out.println("hello");
    }
}

If you don't like dealing with the exception, and if it's worth it for you, you could wrap it like this

import com.google.common.io.Closer;
import lombok.Cleanup;
import lombok.SneakyThrows;
import java.io.Closeable;
import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        @Cleanup Defer defer = Defer.create();
        defer.register(() -> System.out.println("world"));
        System.out.println("hello");
    }
}

// in some util package
class Defer implements Closeable {
    private final Closer closer;

    private Defer(Closer closer) {
        this.closer = closer;
    }

    public static Defer create() {
        return new Defer(Closer.create());
    }

    public <C extends Closeable> C register(C closeable) {
        return this.closer.register(closeable);
    }

    @SneakyThrows(IOException.class)
    @Override
    public void close() {
        this.closer.close();
    }
}
Pawel Zieminski
  • 439
  • 3
  • 8