gpt4 book ai didi

proxy - 为什么jdk动态代理实现中没有使用参数 'proxy'?

转载 作者:行者123 更新时间:2023-11-30 04:48:01 26 4
gpt4 key购买 nike

我在这里阅读了有关代理的示例: http://docs.oracle.com/javase/1.3/docs/guide/reflection/proxy.html

可以看到,'invoke'方法中的参数'proxy'没有被使用。代理是用来做什么的?为什么不在此处使用它: result = m.invoke(proxy, args); ?

public class DebugProxy implements java.lang.reflect.InvocationHandler {

private Object obj;

public static Object newInstance(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new DebugProxy(obj));
}

private DebugProxy(Object obj) {
this.obj = obj;
}

public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable
{
Object result;
try {
System.out.println("before method " + m.getName());
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " +
e.getMessage());
} finally {
System.out.println("after method " + m.getName());
}
return result;
}

}

最佳答案

proxy是JVM专门构建的“动态代理”类。您的代码无法直接调用它的方法。另一种思考方式是,代理是“接口(interface)”,调用其上的任何方法都对应于调用public Object invoke(Object proxy, Method m, Object[] args) 方法,因此调用代理上的方法将会以无限循环结束。

关于proxy - 为什么jdk动态代理实现中没有使用参数 'proxy'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10516038/

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