|
Java™ by example!
|
|
|
How do I get started with writing a dynamic proxy class?
The following example uses a dynamic proxy class to keep track of how much time it takes to execute a method. Two classes are implemented: JMSTransporter and TibcoTransporter, both implementing the interface Transporter.
Suppose we need to do some performance tests to see how long each transporter takes to perform its task. The typical way of doing this is to record a timestamp in the beginning of the method and at the end and printing out the difference:
We would have to do that for the TibcoTransporter as well as the JMSTransporter. It also uglifies the code, makes it harder to maintain (remove when it goes in production) and may introduce bugs. You could also write a wrapper around it, but this is a tedious task and would require you to do this for every interface. Since JDK1.3, you can simplify this task using a dynamic proxy class. A dynamic proxy class is a class that implements a list of interfaces at runtime. An instance of this class can handle method invocations of the interface(s) and dispatches them to the object that implements the interface. Writing a proxy class is simple: implement the InvocationHandler interface and its method
To instantiate a proxy object:
In our example, the proxy class TimerProxy is created. All method invocations to the interfaces that were specified when instantiating the proxy object with newProxyInstance are dispatched to the TimerProxy.
Main.java:
outputs:
Other uses for a dynamic proxy are logging, parameter validation, access control, error handling, ... For more information on Dynamic Proxy Classes, check here
Further Information
Author of answer: Joris Van den Bogaert
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|