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

前端 未结 1 1037
情话喂你
情话喂你 2020-12-21 05:23

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 e

相关标签:
1条回答
  • 2020-12-21 06:05

    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.

    0 讨论(0)
提交回复
热议问题