Proxy pattern and java.lang.reflect.Proxy/InvocationHandler
I looked at the dynamic proxy classes the JDK has to offer
(java.lang.reflect.Proxy and jlr.InvocationHandler etc.). The setup
with the generated proxy calling on the InvocationHandler via
reflection looks nice at first. However, I wonder what the advantages
of this approach are.
The generated proxy forwards all method calls to the invocation
handler. Like that not every method of the proxy's super interface/s
has/have to be implemented as with "standard" (self coded) proxies.
When implementing the invocation handler concrete class'
Object invoke(Object proxy, Method method, Object args)
method you get one method in which you have to (likely) implement all
method bodies anyway. Additionally, you have to do this in/with some
if or switch statement (which method got called?)
if ( method.getName().equals("getBla") )
else if ( method.getName().equals("setBle") )
and so on. Furthermore you need (ugly and probably unnecessary)
downcasts from Object (e.g. to get the parameters). I also don't like
the required interfaces thing with the generated proxies (I use many
abstract classes with common implementations).
So what's the advantage here? Why should anyone use those classes
instead of their own? (please note I won't be using RMI)
Were those classes just a step for improving the RMI API
Re: Proxy pattern and java.lang.reflect.Proxy/InvocationHandler
Karsten Wutzke wrote:
> When implementing the invocation handler concrete class'
> Object invoke(Object proxy, Method method, Object args)
> method you get one method in which you have to (likely) implement all
> method bodies anyway. Additionally, you have to do this in/with some
> if or switch statement (which method got called?)
I don't think you're ever expected to implement each method individually
- there'd be no advantage over implementing a proxy manually. The
purpose is to insert some extra functionality that doesn't depend
specifically on the identity of the method, e.g. logging the call.
A project I was involved in used proxies to execute the method -
otherwise unchanged - in a separate thread, thus preventing threads from
separate modules tangling up in each other's locks. The
InvocationHandler merely had to create an anonymous Runnable to execute
the call, and shove it in a queue - no need to have specific knowledge
of any method. Obviously, it had to do something special (such as
throwing a RuntimeException) with methods that returned non-void, but
that could be determined from aspects of the provided Method argument,
not by identifying a specific method.
ss at comp dot lancs dot ac dot uk |
|All times are GMT. The time now is 06:28 AM.|
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.