mainメソッドからエンクロージングクラスの変数を参照する
- 変数を参照する場合、finalが強要される
- エンクロージングクラスのフィールドならOK
- 実行順を強制できる以外は、利便性はその1とあまり変わらない
- その1よりも複雑なため利点が薄れる
package com.kanasansoft.CloseableUtility; | |
import java.io.Closeable; | |
import java.io.IOException; | |
import java.util.Arrays; | |
import java.util.List; | |
public abstract class CloseableUtility { | |
public CloseableUtility(Closeable... closeables) throws IOException { | |
main(); | |
closeAll(closeables); | |
} | |
abstract public void main() throws IOException; | |
private void closeAll(Closeable... closeables) throws IOException { | |
closeAll(Arrays.asList(closeables)); | |
} | |
private void closeAll(List<Closeable> closeables) throws IOException { | |
if (closeables.isEmpty()) { | |
return; | |
} | |
try { | |
if (closeables.get(0) != null) { | |
closeables.get(0).close(); | |
} | |
} catch (IOException e) { | |
throw e; | |
} finally { | |
closeAll(closeables.subList(1, closeables.size())); | |
} | |
} | |
} |
import java.io.ByteArrayInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.IOException; | |
import com.kanasansoft.CloseableUtility.CloseableUtility; | |
public class Usage { | |
public static void main(String[] args) { | |
new Usage(); | |
} | |
public Usage() { | |
final ByteArrayInputStream is1 = new ByteArrayInputStream(new byte[]{}); | |
final ByteArrayInputStream is2 = new ByteArrayInputStream(new byte[]{}); | |
final ByteArrayOutputStream os1 = new ByteArrayOutputStream(); | |
final ByteArrayOutputStream os2 = new ByteArrayOutputStream(); | |
try { | |
new CloseableUtility(is1, is2, os1, os2){ | |
@Override | |
public void main() throws IOException { | |
//ex. | |
//is1.read(); | |
//is2.read(); | |
//os1.write(new byte[]{}); | |
//os2.write(new byte[]{}); | |
} | |
}; | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |