手慰み。
かっとなってやった。反省はしていない。
- 適用前のコード
InputStream in = null; try { byte[] bytes = stb.toString().getBytes("UTF-8"); in = new ByteArrayInputStream(bytes); f.create(in, IResource.FORCE, null); f.getParent().refreshLocal(IResource.DEPTH_ONE, null); } catch (Exception e) { Activator.log(e); } finally { close(in); }
- 書いたユーティリティ
public class StreamUtil { public interface _<STREAM, T extends Throwable> { STREAM open() throws T; void handle(STREAM in) throws T; void happen(T exception); } @SuppressWarnings("unchecked") public static <STREAM extends InputStream, T extends Throwable> void is( _<STREAM, T> handler) { STREAM in = null; try { in = handler.open(); handler.handle(in); } catch (Throwable e) { handler.happen((T) e); } finally { close(in); } } @SuppressWarnings("unchecked") public static <STREAM extends OutputStream, T extends Throwable> void os( _<STREAM, T> handler) { STREAM out = null; try { out = handler.open(); handler.handle(out); } catch (Throwable e) { handler.happen((T) e); } finally { close(out); } } public static void close(InputStream in) { try { if (in != null) { in.close(); } } catch (IOException e) { throw new IllegalStateException(e); } } public static void close(OutputStream out) { try { if (out != null) { out.close(); } } catch (IOException e) { throw new IllegalStateException(e); } } }
- 適用後のコード
is(new _<InputStream, Exception>() { @Override public InputStream open() throws IOException { byte[] bytes = stb.toString().getBytes("UTF-8"); return new ByteArrayInputStream(bytes); } @Override public void handle(InputStream in) throws Exception { f.create(in, IResource.FORCE, null); f.getParent().refreshLocal(IResource.DEPTH_ONE, null); } @Override public void happen(Exception e) { Activator.log(e); } });
Scala使えとか、言わないでクダサシ。