Re: Method invocation via proxy and reflection
On Oct 1, 3:48 pm, Piotr Kobzda <pi...@gazeta.pl> wrote:
Stefan Ram wrote:
I might have made some mistake. But in this case, I would
expect an exception or an error. Instead silently the wrong
method =BBBase#dummy0()=AB is called. Why?
Because you are trying to cheat Java doing something which is not
normally allowed -- i.e. change private data of a Method. It succeeds
because there is no security manager active, but run it with even
default SM (-Djava.security.manager) and you'll see an exception.
The result "147" is because Java usually optimizes method invocations.
It just happened that length() is declared as first method in
CharSequence, so instead of expected invocation of length() in Delegate,
Java just invokes a first method from it.
One solution to what you are trying to achieve is already mentioned by
Daniel -- implement CharSequence by Delegate and call it directly with a
Method passed to invoke().
Another solution is to use a Map<Method, Method> (most likely HashMap)
for mappings of source CharSequence methods into Delegate methods.
Alternatively you may generate "bridge" methods using e.g. ASM, or cglib.
piotr
Yet another, probably most appropriate, solution is to implement
CharSequence and delegate manually.
Proxy is use most useful for doing things between the calling code and
the called code, or deciding on targets (that already implement the
interfaces) after the call. I've used it to dispatch calls to a list
of targets, such as Listeners. In general, Proxy is a sophisticated
reflection tool, and should be avoided unless you have an excellent
reason to use it ;-)