Re: Create Dynamic Proxy for class instead of interface
On 06/12/2011 04:40 PM, Stanimir Stamenkov wrote:
Sun, 12 Jun 2011 17:15:17 +0300, /Stanimir Stamenkov/:
http://en.wikipedia.org/wiki/Javassist
I basically want to create a proxy augmenting an existing object
with additional interface. Is the Javassist library the right tool
for doing this?
I've found javassist.util.proxy.ProxyFactory does exactly what I want:
http://www.csg.is.titech.ac.jp/~chiba/javassist/html/javassist/util/proxy/ProxyFactory.html
I do not think you can change the behavior of an existing _object_ -
even for changing behavior of an existing _class_ you would have to
resort to manipulating a class's bytecode.
Are there other similar tools?
If you read closely what the Javadoc of ProxyFactory say, you will
notice that you get a _new_ class which is a _subclass_ of the class
that you want to augment. For that you do not need proxy mechanisms.
In fact it is much simpler to inherit the class and make the new class
implement additional interfaces.
The hard bit though (and that's where also the proxy approach fails) is
to manipulate the code which creates instances to no longer create
instances of the given class but instances of the new class (be it via
proxy or plain inheritance). Again, proxy does not help you here - you
will need to find all places with Class.forName("the.original.Class")
and replace them with Class.forName("the.new.Class"). If your given
class is created via some kind of factory mechanism (or the name is
configurable somewhere) it will be much simpler to do the exchange.
Why do you need to manipulate an existing class?
Kind regards
robert