如何使用 AOP 在参数上拦截 super 中的方法调用? [英] How to use AOP to intercept a method call in super on an argument?

查看:32
本文介绍了如何使用 AOP 在参数上拦截 super 中的方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在扩展一个类并覆盖一个方法.我想要做的就是调用 super,但是使用一个修改后的参数,该参数在调用其方法之一时被拦截.一个例子更清楚:

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?

推荐答案

鉴于 Foo 是一个接口,您可以考虑使用 动态代理:

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

  1. 包裹原来的 foo
  2. 拦截所有消息并转发给原始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(...);

请注意,如果 Foo 不是接口,您仍然可以继承 Foo 并手动覆盖所有方法以转发它们.

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(); }

    ...
}

这是伪代码,我还没有测试过.在这两种情况下,包装器都允许您拦截 super 中的调用.

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

当然,包装器和原来的Foo不是同一个类,所以如果super使用

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

  1. 反思
  2. 实例
  3. 或直接访问实例变量(不通过 getter/setter)

,那么它可能有问题.

希望我正确理解您的问题并且它有所帮助.

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

这篇关于如何使用 AOP 在参数上拦截 super 中的方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆