中国开发网: 论坛: 程序员情感CBD: 贴子 441221
nostalgic
请大牛入内.
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyTest {
public PrintInterface proxyTest(PrintInterface print) {
Object obj = Proxy.newProxyInstance(PrintInterface.class
.getClassLoader(), new Class[] { PrintInterface.class },
new MyInvocationHandler(print));
PrintInterface printToUse = (PrintInterface) obj;
return printToUse;

}

public static class MyInvocationHandler implements InvocationHandler {

private final PrintInterface print;

public MyInvocationHandler(PrintInterface print) {
this.print = print;
}

public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
try {
Object retVal = method.invoke(this.print, args);


return retVal;
} catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
}




PrintInterface printToUser = proxyTest.proxyTest(print);
print.print("\nprint by itself\n");
printToUser.print("\nprint by proxy");



public static class MyInvocationHandler implements InvocationHandler

这个方法返回的retVal是null,是可以的,可是Y的,不应该返回NULL的,不知道为何返回了NULL,可否指点?还有偶改写这个方法,让它直接返回null.

PrintInterface printToUser = proxyTest.proxyTest(print);
print.print("\nprint by itself\n");
printToUser.print("\nprint by proxy");

这个地方竟然不输出 printToUser.print("\nprint by proxy");

相关信息:


欢迎光临本社区,您还没有登录,不能发贴子。请在 这里登录