防止API中的System.exit() [英] Preventing System.exit() from API

查看:74
本文介绍了防止API中的System.exit()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果遇到异常,我正在使用第三方库来执行 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 ) ;
  }






编辑最大值在下面的评论中指出


Edit: Max points out in comments below that


从Java 6开始,权限名称实际上是exitVM。+ status,例如exitVM.0。

as of Java 6, the permission name is actually "exitVM."+status, e.g. "exitVM.0".

但是,权限 exitVM。* 是指对于所有退出状态, exitVM 将保留为 exitVM。* 的简写,因此上述代码仍然有效(请参阅 RuntimePermission <的文档/ code> )。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆