从 API 中防止 System.exit() [英] Preventing System.exit() from API
问题描述
我正在使用第三方库,如果遇到异常,它会执行 System.exit()
.我正在使用 jar 中的 API.无论如何我可以阻止 System.exit()
调用,因为它会导致我的应用程序关闭?由于许多其他许可问题,我无法在删除 System.exit()
后反编译和重新编译 jar.我曾经在 stackoverflow 中遇到过[其他一些我不记得的问题] 的答案,我们可以使用 Java 中的 SecurityManager
来做这样的事情.
I am using a third party library that does a System.exit()
if it encounters exceptions. I am using the APIs from a jar. Is there anyway that I can prevent the System.exit()
call because it causes my application to shutdown? I cannot decompile and recompile the jar after removing the System.exit()
because of a lot of other licensing issues. I once came across an answer [to some other question that I do not remember] in stackoverflow that we can use the SecurityManager
in Java to do something like this.
推荐答案
这里有一篇博文,
http://jroller.com/ethdsy/entry/disabling_system_exit
基本上它会安装一个安全管理器,该管理器使用来自此处的代码禁用 System.exit(),
Basically it installs a security manager which disables System.exit() with code from here,
private static class ExitTrappedException extends SecurityException { }
private static void forbidSystemExitCall() {
final SecurityManager securityManager = new SecurityManager() {
public void checkPermission( Permission permission ) {
if( "exitVM".equals( permission.getName() ) ) {
throw new ExitTrappedException() ;
}
}
} ;
System.setSecurityManager( securityManager ) ;
}
private static void enableSystemExitCall() {
System.setSecurityManager( null ) ;
}
<小时>
编辑:Max在下面的评论中指出
从 Java 6 开始,权限名称实际上是exitVM."+status,例如exitVM.0".
as of Java 6, the permission name is actually "exitVM."+status, e.g. "exitVM.0".
然而,权限exitVM.*
指的是所有退出状态,而exitVM
保留为exitVM.*
的简写,所以上面的代码仍然有效(请参阅 的文档运行时权限
).
However, the permission exitVM.*
refers to all exit statuses, and exitVM
is retained as a shorthand for exitVM.*
, so the above code still works (see the documentation for RuntimePermission
).
这篇关于从 API 中防止 System.exit()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!