Using the Security Manager
We’re now going to examine the public methods of the security manager so that we may understand how the security manager is used by applications and by the Java API.
Setting a Security Manager
There are two methods in the
System class that are used to work with the
security manager itself:
- public static SecurityManager getSecurityManager()
Return a reference to the currently installed security manager object (or
nullif no security manager is in place). Once obtained, this object can be used to test against various security policies.- public static void setSecurityManager(SecurityManager sm)
Set the system’s security manager to the given object. This method can only be called once, and once installed, the security manager cannot be removed. Attempting to call this method after a security manger has already been installed will result in a
SecurityException.
These methods operate with the understanding that there is a single security manager in the virtual machine; the only operations that are possible on the security manager are setting it (that is, creating an instance of the security manager class and telling the virtual machine that the newly created object should be the security manager), and getting it (that is, asking the virtual machine to return the object that is the security manager so that a method might be invoked upon it).
We’ve already seen how you might use the
getSecurityManager() method to retrieve the security manager and invoke an operation ...