tags:

views:

178

answers:

1

I'm extending a class and overriding a method. All I want to do is to call super, but with a modified argument that gets intercepted upon one of its methods is called. An example makes it more clear:

// Foo is an interface and also this method is part of an interface
@Override
public void foo(Foo foo) {
    // I want to intercept the call to foo.bar() in super
    super.foo(foo);
}

I'd rather use a tool that doesn't require a compiler of its own. What would be the optimal one?

+1  A: 

Given that Foo is an interface, you might consider using a dynamic proxy that would:

  1. Wrap the original foo
  2. Intercept all message and forward them to the original foo

There is a complete example in the above link. Here is just the idea:

public class DebugProxy implements java.lang.reflect.InvocationHandler {

   private Object obj;

   private DebugProxy(Object obj) {
      this.obj = obj;
   }

   public Object invoke(Object proxy, Method m, Object[] args) throws Throwable
   {
       System.out.println("before method " + m.getName());
       return m.invoke(obj, args); 
   }
}

Foo original = ... ;
Foo wrapper = (Foo) java.lang.reflect.Proxy.newProxyInstance(
    original.getClass().getClassLoader(),
    original.getClass().getInterfaces(),
    new DebugProxy(original));
wrapper.bar(...);

Note that if Foo was not an interface, you could still subclass Foo and override all methods manually so as to forward them.

class SubFoo extends Foo
{
    Foo target;

    SubFoo( Foo target ) { this.target = target };

    public void method1() { target.method1(); }

    ...
}

It's pseudo-code, and I haven't tested it. In both cases, the wrapper allows you to intercept a call in super.

Of course, the wrapper has not the same class as the original Foo, so if super uses

  1. reflection
  2. instanceof
  3. or access instance variables directly (not going through getter/setter)

, then it might be problematic.

Hope that I understood your problem right and that it helps.

ewernli
This is it. I was thinking of way too difficult solution. Thanks for bringing me back to the ground level.
hleinone