esuslogo
 [To advertise Java(tm) Events here, contact joris@esus.com!]
banner

Java™
by example!






New @ Esus.com


  gb  In-house search engine for better results!

  gb  Get updates with the esus.com
newsletter!









  Home 
 Browse Categories 
 Ask a Java Question 
 Help 
  For Java Tips & Tricks, subscribe to the esus.com newsletter!
Search Java Q&A, Links, API's:   adv 

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.

 
This code sample is only viewable to esus.com members
Login or become a member!


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:

 
This code sample is only viewable to esus.com members
Login or become a member!


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

 
This code sample is only viewable to esus.com members
Login or become a member!


To instantiate a proxy object:

 
This code sample is only viewable to esus.com members
Login or become a member!


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:

This code sample is only viewable to esus.com members
Login or become a member!


outputs:

 
This code sample is only viewable to esus.com members
Login or become a member!


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!





Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 Esus.com - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. Esus.com is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.