java 如何防止对 System.exit() 的调用终止 JVM?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5549720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to prevent calls to System.exit() from terminating the JVM?
提问by Tiago Veloso
I am almost certain this is impossible, but it's worth a try.
我几乎可以肯定这是不可能的,但值得一试。
I am writing a command line interface for a certain tool. I am talking about a Java application that invokes another Java application. The tool calls System.exit
after execution, which in turn terminates my own execution environment. I don't want that.
我正在为某个工具编写命令行界面。我说的是调用另一个 Java 应用程序的 Java 应用程序。该工具System.exit
在执行后调用,这反过来终止了我自己的执行环境。我不想要那个。
Is there any way to ignore System.exit
calls?
有什么办法可以忽略System.exit
电话吗?
采纳答案by theomega
Yes, this is possible using a SecurityManager. Try the following
是的,这可以使用 SecurityManager 实现。尝试以下
class MySecurityManager extends SecurityManager {
@Override public void checkExit(int status) {
throw new SecurityException();
}
@Override public void checkPermission(Permission perm) {
// Allow other activities by default
}
}
In your class use the following calls:
在您的课程中使用以下调用:
myMethod() {
//Before running the external Command
MySecurityManager secManager = new MySecurityManager();
System.setSecurityManager(secManager);
try {
invokeExternal();
} catch (SecurityException e) {
//Do something if the external code used System.exit()
}
}
回答by Peter Lawrey
Set the SecurityManagerto ignore System.exit(), unless it comes from your code.
将SecurityManager设置为忽略 System.exit(),除非它来自您的代码。
回答by codymanix
You can break your application in two parts. The first one gets started by the tool. Then you launch the second part of your application as a new process. Then the host application kills your first part, but the second part is still running.
您可以将应用程序分为两部分。第一个由该工具启动。然后将应用程序的第二部分作为新进程启动。然后主机应用程序杀死您的第一部分,但第二部分仍在运行。
This way the first part of your app is just the startup for the second part which is in turn your real application.
这样,您的应用程序的第一部分只是第二部分的启动,而第二部分又是您的实际应用程序。
回答by lukastymo
Regarding to this (@Vonc answer)you should use Security Manager:
关于这个(@Vonc 回答)你应该使用安全管理器:
Try modifying the TestCase to run with a security manager that prevents calling System.exit, then catch the SecurityException.
尝试修改 TestCase 以与阻止调用 System.exit 的安全管理器一起运行,然后捕获 SecurityException。