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

前端 未结 4 1091
自闭症患者
自闭症患者 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: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()
        }
    }
    

提交回复
热议问题