如何使用标准java功能拦截方法调用(没有AspectJ等)? [英] How do I intercept a method invocation with standard java features (no AspectJ etc)?
问题描述
我想拦截所有方法调用到某个类MyClass,以便能够对某些setter-invocations做出反应。
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(JAR包含在Spring中),你可以做以下内容:
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等)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!