如何防止调用System.exit()终止JVM? [英] How to prevent calls to System.exit() from terminating the JVM?

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

问题描述

我几乎可以肯定这是不可能的,但值得一试。

I am almost certain this is impossible, but it's worth a try.

我正在为某个工具编写命令行界面。我在谈论调用另一个Java应用程序的Java应用程序。该工具在执行后调用 System.exit ,从而终止我自己的执行环境。我不希望这样。

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.

有没有办法忽略 System.exit 来电?

推荐答案

是的,这可以使用SecurityManager。请尝试以下方法

Yes, this is possible using a SecurityManager. Try the following

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()
    }
}

这篇关于如何防止调用System.exit()终止JVM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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