Joe*_*dev 5 java proxy dynamic
我有一个与java中的动态代理有关的问题.
假设我有一个Foo用方法execute和类调用的接口FooImpl implements Foo.
当我创建代理时Foo,我有类似的东西:
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class },
handler);
Run Code Online (Sandbox Code Playgroud)
假设我的调用处理程序如下所示:
public class FooHandler implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
如果我的调用代码看起来像
Foo proxyFoo = (Foo) Proxy.newInstance(Foo.getClass().getClassLoader(),
new Class[] { Foo.class },
new FooHandler());
proxyFoo.execute();
Run Code Online (Sandbox Code Playgroud)
如果代理可以execute从Foo界面拦截上述呼叫,那么它FooImpl可以在哪里播放?也许我正在以错误的方式查看动态代理.我想要的是能够execute从具体实现中捕获调用Foo,例如FooImpl.可以这样做吗?
非常感谢
使用动态代理拦截方法的方法是:
public class FooHandler implements InvocationHandler {
private Object realObject;
public FooHandler (Object real) {
realObject=real;
}
public Object invoke(Object target, Method method, Object[] arguments) throws Throwable {
if ("execute".equals(method.getName()) {
// intercept method named "execute"
}
// invoke the original methods
return method.invoke(realObject, arguments);
}
}
Run Code Online (Sandbox Code Playgroud)
通过以下方式调用代理:
Foo foo = (Foo) Proxy.newProxyInstance(
Foo.class.getClassLoader(),
new Class[] {Foo.class},
new FooHandler(new FooImpl()));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2937 次 |
| 最近记录: |