本文介绍了如何拦截具有标准 Java 功能(无 AspectJ 等)的方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拦截对某个类 MyClass 的所有方法调用,以便能够对某些 setter 调用做出反应.

I want to intercept all method invocations to some class MyClass to be able to react on some setter-invocations.

我尝试使用动态代理,但据我所知,这只适用于实现某些接口的类.但是MyClass没有这样的接口.

I tried to use dynamic proxies, but as far as I know, this only works for classes implementing some interface. But MyClass does not have such an interface.

除了实现包装类之外,还有什么其他方法可以将所有调用委托给一个成员,该成员是 MyClass 的一个实例或除了使用 AOP 之外?

Is there any other way, besides implementing a wrapper class, that delegates all invocations to a member, which is an instance of the MyClass or besided using AOP?

推荐答案

正如您所注意到的,您不能使用 JDK 动态代理(无接口),而是使用 Spring 和 CGLIB(Spring 包含的 JAR),您可以执行以下操作:

As you note, you cannot use JDK dynamic proxies (no interface), but using Spring and CGLIB (JAR included with Spring), you can do the following:

public class Foo
{
    public void setBar()
    {
        throw new UnsupportedOperationException("should not go here");
    }

    public void redirected()
    {
        System.out.println("Yiha");
    }
}

Foo foo = new Foo();
ProxyFactory pf = new ProxyFactory(foo);

pf.addAdvice(new MethodInterceptor()
{
    public Object invoke(MethodInvocation mi) throws Throwable
    {
        if (mi.getMethod().getName().startsWith("set"))
        {
            Method redirect = mi.getThis().getClass().getMethod("redirected");
            redirect.invoke(mi.getThis());
        }
        return null;
    }
});

Foo proxy = (Foo) pf.getProxy();
proxy.setBar(); // prints "Yiha"

这篇关于如何拦截具有标准 Java 功能(无 AspectJ 等)的方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 05:05