gpt4 book ai didi

Java 动态代理 - 如何引用具体类

转载 作者:搜寻专家 更新时间:2023-10-31 20:06:30 24 4
gpt4 key购买 nike

我有一个关于 java 中的动态代理的问题。

假设我有一个名为 Foo 的接口(interface),带有方法 execute 和类 FooImpl implements 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();

如果代理可以从Foo接口(interface)拦截上述调用execute,那么FooImpl从哪里来发挥作用?也许我以错误的方式看待动态代理。我想要的是能够从 Foo 的具体实现中捕获 execute 调用,例如 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);
}
}

通过以下方式调用代理:

Foo foo = (Foo) Proxy.newProxyInstance(
Foo.class.getClassLoader(),
new Class[] {Foo.class},
new FooHandler(new FooImpl()));

关于Java 动态代理 - 如何引用具体类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5167185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com