Search code examples
javasecuritymanager

How can I determine what class called System.exit() from the checkExit() method of a custom SecurityManager?


I am writing a SecurityManager that should only allow System.exit() calls from a single class. The problem is that this class is also the one containing the main() method which is running the app, so using SecurityManager.inClass() won't work - we're always in that class. I need to know if that class is the one that explicitly is trying to exit or not. Is this possible at all?


Solution

  • Putting it all together:

    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    String className = stacktraceElements[stackTraceElements.length-1].getClassName();
    if (className.contains("MainClassName")){
    }
    

    Alternatively, you can loop over the stackTraceElements to see if any of them are your main class (or make sure the "correct" one is).

    Here is how I found out all this:

    See this question on how to get the stack trace: Get current stack trace in Java

    Once you have the array of StackTraceElements, you can get the last one, and then get the class from that one. (the last StackTraceElement is the most recent one)

    See this question to get a class from the stack trace: How do I find the caller of a method using stacktrace or reflection?

    Actually, by the looks of it, you can more easily get the class name, which you can easily use to do a String.equals() check:

    if(className.equals("MainClassName")){
    }
    

    As it turns out, the class name has package info in it too, according to http://docs.oracle.com/javase/7/docs/api/java/lang/StackTraceElement.html. So use String.contains() instead.