How to prevent calls to System.exit() from terminating the JVM?

前端 未结 4 1013
自闭症患者
自闭症患者 2020-12-03 13:33

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 i

相关标签:
4条回答
  • 2020-12-03 14:03

    Set the SecurityManager to ignore System.exit(), unless it comes from your code.

    0 讨论(0)
  • 2020-12-03 14:05

    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.

    0 讨论(0)
  • 2020-12-03 14:17

    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()
        }
    }
    
    0 讨论(0)
  • 2020-12-03 14:18

    Regarding to this (@Vonc answer) you should use Security Manager:

    Try modifying the TestCase to run with a security manager that prevents calling System.exit, then catch the SecurityException.

    0 讨论(0)
提交回复
热议问题