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();
}
}