前書き#
TopicCommand.main(args)
zookeeper を使用して kafka の topic コマンドを実行する際に遭遇した問題です。オープンソースツールのコード内部で topic の作成が実行される際に、System.exit(0) の操作が行われるため、JVM が終了してしまいます。しかし、ツールのコードを変更することはできないため、System.exit(status) をキャプチャする方法を試してみることができます。
実装#
java.lang からの SecurityManager クラスを継承します。
そして、checkExit(int status) メソッドをオーバーライドします。
static class DemoSecurityManager extends SecurityManager {
@Override public void checkExit(int status) {
throw new SecurityException();
}
}
System.exit(status) を実行するコードブロックの前にこのコードを追加し、このコードを try-catch します。
@Test
void testMain() {
System.out.println("startMain");
DemoSecurityManager demoSecurityManager = new DemoSecurityManager();
System.setSecurityManager(demoSecurityManager);
try {
main(new String[]{});
} catch (Exception e) {
System.err.println("終了エラーのメソッドをスキップして続行します");
}
System.out.println("endMain");
// メモリリークを防ぐため
System.setSecurityManager(null);
}
public static void main(String[] args) {
System.out.println("testMain");
System.exit(0);
}
これにより、最終的な実行結果は次のようになります。
startMain
testMain
endMain