Skip to content

Instantly share code, notes, and snippets.

@hisui
Created June 27, 2017 04:06
Show Gist options
  • Save hisui/78903858df23eb2ed2975355a3196db7 to your computer and use it in GitHub Desktop.
Save hisui/78903858df23eb2ed2975355a3196db7 to your computer and use it in GitHub Desktop.
As it closes, recursively closing every "AutoCloseable" field marked with the "Owns" annotation as well.
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.stream.Stream;
import java.util.stream.Collectors;
public interface AutoCloseable2 extends AutoCloseable {
@Override
public default void close() throws Exception {
for (Field field : getClass().getDeclaredFields()) {
if (field.getAnnotation(Owns.class) != null) {
for (AutoCloseable e : toAutoCloseableObjects(field.get(this)).collect(Collectors.toList())) e.close();
}
}
}
static Stream<AutoCloseable> toAutoCloseableObjects(Object obj) {
if (obj instanceof AutoCloseable) {
return Stream.of((AutoCloseable) obj);
}
if (obj instanceof Collection<?>) {
return ((Collection<?>) obj).stream().flatMap(AutoCloseable2::toAutoCloseableObjects);
}
return Stream.of();
}
}
name := "autoClose"
javacOptions ++= Seq(
"-source" -> "1.8",
"-target" -> "1.8"
).flatMap(_.productIterator.map(_ +""))
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Foo foo = new Foo("parent",
new Foo("child#1",
new Bar("grandchild#1/1", Arrays.asList()),
new Bar("grandchild#1/2", Arrays.asList())
),
new Bar("child#2", Arrays.asList(
new Bar("grandchild#2/1", Arrays.asList()),
new Bar("grandchild#2/2", Arrays.asList())
))
);
foo.close();
}
static class Foo implements AutoCloseable2 {
String key;
@Owns
AutoCloseable bar;
@Owns
AutoCloseable baz;
Foo(String key, AutoCloseable bar, AutoCloseable baz) {
this.key = key;
this.bar = bar;
this.baz = baz;
}
@Override
public void close() throws Exception {
AutoCloseable2.super.close();
System.err.println("Foo@" + key + " is being closed..");
}
}
static class Bar implements AutoCloseable2 {
String key;
@Owns
List<AutoCloseable> children;
Bar(String key, List<AutoCloseable> children) {
this.key = key;
this.children = children;
}
@Override
public void close() throws Exception {
AutoCloseable2.super.close();
System.err.println("Bar@" + key + " is being closed..");
}
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Owns {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment