Java Reference
In-Depth Information
behalf of the user. This requires that the system utility code becomes
privileged while obtaining the fonts.
The
doPrivileged
method of
AccessController
take as an argument a
java.security.PrivilegedAction<T>
object whose
run
method defines the
code to be marked as privileged. For example, your call to
doPrivileged
can look like the following:
void someMethod() {
// ...normal code here...
AccessController.doPrivileged(
new PrivilegedAction<Object>() {
public Object run() {
// privileged code goes here, for example:
System.loadLibrary("awt");
return null; // nothing to return
}
}
);
// ...normal code here...
}
The
doPrivileged
method executes the
run
method in privileged mode.
Privileged execution is a way for a class with a given permission to tem-
porarily grant that permission to the thread that executes the privileged
code. It will not let you gain permissions that you do not already have.
The class defining
someMethod
must have the permission
RuntimePermis-
sion("loadLibrary.awt")
; otherwise, any thread that invokes
someMethod
will get a
SecurityException
. It is guaranteed that privileges will be re-
voked after the
PrivilegedAction
object's
run
method returns.
The
PrivilegedAction<T>
interface's single method
run
returns a
T
object.
Another form of
doPrivileged
takes a
PrivilegedExceptionAction<T>
object,
whose
run
method also returns
T
, but which can throw any checked ex-
ception. For both of these methods there is a second overloaded form of
doPrivileged
that takes an
AccessControlContext
as an argument and uses