There are two methods in the
System
class that are
used to work with the security manager itself:
- public static void setSecurityManager(SecurityManager sm)
Set the system’s security manager to the given object. Code that wants to install a security manager must have the runtime permissions
createSecurityManager
in order to instantiate the security manager object andsetSecurityManager
in order to install it.
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 on it. Setting the security
manager is a predictably simple operation:
public static void main(String args[]) { System.setSecurityManager(new SecurityManagerImpl( )); ... do the work of the application ... } }
The
SecurityManager
class provides a complete implementation
that uses the access controller to implement the permission-based
sandbox we discussed in Chapter 2. When you
specify the -Djava.security.manager
option to a
Java application, the virtual machine executes the
setSecurityManager( )
method on your behalf,
before it calls the main( )
method of your
application.
However, it’s possible to extend the
SecurityManager
class to provide a different
implementation of the sandbox. The Java Plug-in and
appletviewer
use such a modified implementation
and install it before they load any applets. And while the changes
that the Java Plug-in and appletviewer
make are
very minor, other environments can have completely different
implementations.
Get Java Security, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.