Java动态代理-如何引用具体类
我有一个关于java中动态代理的问题。
假设我有一个名为 Foo
的接口,其中包含一个 execute
方法,并且类 FooImpl 实现了 Foo
。
当我为 Foo
创建代理时,我有类似以下内容:
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class },
handler);
假设我的调用处理程序如下所示:
public class FooHandler implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) {
...
}
}
如果我的调用代码类似于
Foo proxyFoo = (Foo) Proxy.newInstance(Foo.getClass().getClassLoader(),
new Class[] { Foo.class },
new FooHandler());
proxyFoo.execute();
如果代理可以拦截上述调用 execute
从 Foo
接口来看,FooImpl
在哪里发挥作用?也许我以错误的方式看待动态代理。我想要的是能够从 Foo
的具体实现(例如 FooImpl
)捕获 execute
调用。这可以做到吗?
非常感谢
I have a question relating to dynamic proxies in java.
Suppose I have an interface called Foo
with a method execute
and class FooImpl implements Foo
.
When I create a proxy for Foo
and I have something like:
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class },
handler);
Suppose my invocation handler looks like:
public class FooHandler implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) {
...
}
}
If my invocation code looks something like
Foo proxyFoo = (Foo) Proxy.newInstance(Foo.getClass().getClassLoader(),
new Class[] { Foo.class },
new FooHandler());
proxyFoo.execute();
If the proxy can intercept the aforementioned call execute
from the Foo
interface, where does the FooImpl
come in to play? Maybe I am looking at dynamic proxies in the wrong way. What I want is to be able to catch the execute
call from a concrete implementation of Foo
, such as FooImpl
. Can this be done?
Many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用动态代理拦截方法的方法是: 通过以下方式
调用代理:
The way to intercept methods using dynamic proxies are by:
Invoke the proxy by:
如果您想委托给某些 Foo 实现(例如 FooImpl),只需将您的 InitationHandler 设为其他 Foo 实例的包装器(传递给构造函数),然后发送 FooImpl 实例作为委托即可。然后,在
handler.invoke()
方法内,调用 method.invoke(delegate, args)。If you want to delegate to some Foo implementation like FooImpl, just make your InvocationHandler a wrapper of an other Foo instance (passed to the constructor) and then send a FooImpl instance as the delegate. Then, inside the
handler.invoke()
method, call method.invoke(delegate, args).