Proxy 为什么参数';代理';在jdk动态代理实现中没有使用?
我在这里阅读了有关代理的示例: 如您所见,“invoke”方法中的参数“proxy”未使用。代理用于什么?为什么不在这里使用它:result=m.invoke(proxy,args)Proxy 为什么参数';代理';在jdk动态代理实现中没有使用?,proxy,java,Proxy,Java,我在这里阅读了有关代理的示例: 如您所见,“invoke”方法中的参数“proxy”未使用。代理用于什么?为什么不在这里使用它:result=m.invoke(proxy,args) }代理是由JVM“动态代理”类专门构造的。您的代码无法直接调用其方法。考虑这一点的另一种方式是代理是“接口”,调用其上的任何方法都对应于调用公共对象调用(对象代理,方法m,对象[]args)方法,因此在代理上调用方法将以无限循环结束。谢谢您的回答。为什么我们有参数,因为我们不能使用它。为什么不隐藏它?如果不需要花
}代理是由JVM“动态代理”类专门构造的。您的代码无法直接调用其方法。考虑这一点的另一种方式是代理是“接口”,调用其上的任何方法都对应于调用
公共对象调用(对象代理,方法m,对象[]args)
方法,因此在代理上调用方法将以无限循环结束。谢谢您的回答。为什么我们有参数,因为我们不能使用它。为什么不隐藏它?如果不需要花费成本就可以隐藏它。:-)也许您想要内省这个类(例如,调用getClass()方法)。
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;
}