Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

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

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 invokes another Java application. The tool calls System.exit after execution, which in turn terminates my own execution environment. I don't want that.

Is there any way to ignore System.exit calls?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...