Proxy Objects
Java 1.3 added the Proxy
class and InvocationHandler
interface to the java.lang.reflect
package. This pair allows the creation of synthetic “proxy objects”:
objects that implement one or more specified interfaces, with method
invocations handled by an InvocationHandler
object. The key method is
Proxy.newProxyInstance( )
. This is
an advanced reflection feature, and it is not commonly needed in
day-to-day Java programming. It is quite useful for certain tasks,
however, such as integrating scripting languages with Java.
Example 9-3 builds on
the Command
class. The static
create( )
method returns a newly
created proxy object that invokes a specified interface using a
Map
that associates Command
objects with method names. The inner
class Test
provides a GUI-based
demonstration like that included with the Command
example.
Example 9-3. CommandProxy.java
package je3.reflect; import java.lang.reflect.*; import java.util.*; import javax.swing.*; import java.awt.event.*; /** * This class is an InvocationHandler based on a Map of method names to Command * objects. When the invoke( ) method is called, the name of the method to be * invoked is looked up in the map, and the associated Command, if any, is * invoked. Arguments passed to invoke( ) are always ignored. Note that there * is no public constructor for this class. Instead, there is a static factory * method for creating Proxy objects that use an instance of this class. * Pass the interface to be implemented and a Map of name/Command ...
Get Java Examples in a Nutshell, 3rd 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.