Preface#
TopicCommand.main(args)
Encountered a problem when executing the command to create a topic
in kafka
using zookeeper
. In the code of the open-source tool, when creating the topic
, it eventually performs a System.exit(0)
operation, which terminates our JVM
. At this point, we cannot modify the code of the tool, so we can try to catch System.exit(status)
from a different perspective.
Implementation#
Inherit from the SecurityManager
class, which is from java.lang
.
Then override the checkExit(int status)
method.
static class DemoSecurityManager extends SecurityManager {
@Override public void checkExit(int status) {
throw new SecurityException();
}
}
Add this code before the code block that will execute System.exit(status)
, and try-catch
this code.
@Test
void testMain() {
System.out.println("startMain");
DemoSecurityManager demoSecurityManager = new DemoSecurityManager();
System.setSecurityManager(demoSecurityManager);
try {
main(new String[]{});
} catch (Exception e) {
System.err.println("Skip the method that exits, and continue execution");
}
System.out.println("endMain");
// Prevent memory overflow
System.setSecurityManager(null);
}
public static void main(String[] args) {
System.out.println("testMain");
System.exit(0);
}
This will result in the following execution result:
startMain
testMain
endMain