Java Reference
In-Depth Information
16.12. The
Proxy
Class
The
Proxy
class lets you create classes at runtime that implement one or
more interfaces. This is an advanced, rarely needed feature, but when
needed it is quite useful.
Suppose, for example, you want to log calls to an object so that when
a failure happens you can print the last several methods invoked on the
object. You could write such code by hand for a particular class, with a
way to turn it on for a particular object. But that requires custom code for
each type of object you want to monitor, as well as each object checking
on each method invocation to see if calls should be logged.
You could instead write a general utility that used a
Proxy
-created class to
log a call history. Objects created by that class would implement the rel-
evant interfaces, interposing code that you provide between the caller's
invocation of a method and the object's execution of it.
The
Proxy
model is that you invoke
Proxy.getProxyClass
with a class loader
and an array of interfaces to get a
Class
object for the proxy. Proxy ob-
jects have one constructor, to which you pass an
InvocationHandler
ob-
ject. You can get a
Constructor
object for this constructor from the
Class
object and use
newInstance
(passing in an invocation handler) to create a
proxy object. The created object implements all the interfaces that were
passed to
getProxyClass
, as well as the methods of
Object
. As a shortcut
to get a proxy object, you can invoke
Proxy.newProxyInstance
, which takes
a class loader, an array of interfaces, and an invocation handler. When
methods are invoked on the proxy object, these method invocations are
turned into calls to the invocation handler's
invoke
method.
Given all that, here is how a general debug logging class might look:
public class DebugProxy implements InvocationHandler {
private final Object obj; // underlying object
private final List<Method> methods; // methods invoked
private final List<Method> history; // viewable history
private DebugProxy(Object obj) {