Announcement Announcement Module
No announcement yet.
Changing the method called by a MethodInterceptor Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Changing the method called by a MethodInterceptor

    I am trying to assemble a MethodInterceptor that queues up results from an underlying class. Examples of when to use this might include a Fibboniacci sequence or a list of prime numbers (neither of which are exactly what I'm doing, but that's a different topic). In my case, it makes sense to queue these up because I'm going across to a remote server which is performing the calculations, and I want to minimize network hops.

    I'll use the prime number example for reference.

    I have an Interface as follows:
    public interface PrimeNumberSequencer
    public long getNextPrime();
    public long[] getNextNPrimes(int n);

    In my MethodInterceptor, I already have the logic to determine whether I'm calling the single-result method or the multiple-result method. I also already wired up a queue (currently handled by a Jakarta Commons Unlimited FIFO queue) so I can add and remove values as needed.

    I already have the code working for getNextNPrimes(int). In my invoke() method, I simply clone the MethodInvocation and modify the "n" argument value to return more values than I originally asked for.

    My problem is the code for getNextPrime()... I'd like it to call getNextNPrimes(int) instead of getNextPrime(), if my queue is empty. But I can't figure out how to do this. I can't do it by cloning the MethodInvocation(which is really a ReflectiveMethodInvocation), because I can't set the method after doing the clone. And I can't create a new ReflectiveMethodInvocation with the same values as the original MethodInvocation because I can't access the target class.

    Any ideas?

    Thanks in advance!

  • #2
    You could use reflection to call "invoke".

    getThis will return the target of the proxy. You can then use it to invoke the target using relection:

      Object target = getThis();
      Class clazz = target.getClass();
      Method m = clazz.getMethod("getNextNPrimes", new Class[] {int.class});
      m.invoke(target, new Object[] { new Integer(myInt) });
    Of course in reality you'd want to do some caching do improve the performance of the reflection, but this is the general idea.