Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

java - How to use AOP to intercept a method call in super on an argument?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...