java.io.Closeable の事も忘れないであげて。
public class StreamUtil { public static abstract class using<STREAM extends Closeable, T extends Exception> { public using(Class<T> clazz) { $(this, clazz); } public abstract STREAM open() throws T; public abstract void handle(STREAM stream) throws T; public abstract void happen(T exception); } @SuppressWarnings("unchecked") static <STREAM extends Closeable, T extends Exception> void $( using<STREAM, T> _, Class<T> clazz) { STREAM in = null; try { in = _.open(); _.handle(in); } catch (Exception e) { if (clazz.isAssignableFrom(e.getClass())) { _.happen((T) e); } throw new IORuntimeException(e); } finally { close(in); } } public static void close(Closeable c) { try { if (c != null) { c.close(); } } catch (IOException e) { throw new IORuntimeException(e); } } }
使う時は、こんな感じ。
new using<InputStream, Exception>(Exception.class) { public InputStream open() throws Exception { return new FileInputStream(file); } public void handle(InputStream stream) throws Exception { } public void happen(Exception exception) { logger.log(exception); } };
javaにもusingブロック欲しいなぁ…とか、ずっと思ってる。
このコードは、例外処理の部分が、激しくダサい、誰か何とかしてくれないものか、ポワワ