Search code examples
javasecuritymanagersystem.exit

Allow System.exit only for certain classes


We are having a Java 1.7 application, that supports plugins, which customers can program in Java. We want to restrict the plugins however from calling System.exit. We can do this via a SecurityManager. However, in the core application there are rare situation when we want to call System.exit. Is there a way to exclude classes or packages from a SecurityManager?


Solution

  • I think you are looking for this :

    private static class ExitTrappedException extends SecurityException 
    { 
    } 
    private static void forbidSystemExitCall()
    { 
        final SecurityManager securityManager = new SecurityManager() { 
             public void checkPermission( Permission permission ) 
            { 
                  if( "exitVM".equals( permission.getName() ) ) 
                {  
                        throw new ExitTrappedException() ; 
                }
            }
        } ; 
        System.setSecurityManager( securityManager ) ; 
    } 
    
    private static void enableSystemExitCall() 
    {  
           System.setSecurityManager( null ) ; 
    }
    

    This is inside your class from which plugin is invoked.

    put you plugin call between forbidSystemExitCall and enableSystemExitCall.