这段代码是张孝祥老师将代理时候的代码:
public class ProxyTest {
public static void main(String[] args) throws Exception{
final ArrayList target = new ArrayList();
Collection proxy3 = (Collection)getProxy(target,new MyAdvice());//为什么这里不能直接转换成 ArrayList,我强制转换的结果是出现类型转换异常,为什么?
proxy3.add("zxx");
proxy3.add("lhm");
proxy3.add("bxd");
System.out.println(proxy3.size());
System.out.println(proxy3.getClass().getName());
}
private static Object getProxy(final Object target,final Advice advice) {
Object proxy3 = Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforeMethod(method);
Object retVal = method.invoke(target, args);
advice.afterMethod(method);
return retVal;
}
}
);
return proxy3;
}
}
求高手解答:红色标记的部分。先说我自己的分析,既然返回结果是ArrayList代理的,就应该可以转换成ArrayList,而为什么一定要转换成Collection?
|