@SuppressWarnings("unchecked")
public static void main(String[] args) {
List<Object> proxy = (List<Object>) getProxy(new ArrayList<Object>());
proxy.add("helen");
proxy.add("never");
proxy.add("for");
proxy.remove(1);
System.out.println(proxy);
}
运行到这句List<Object> proxy = (List<Object>) getProxy(new ArrayList<Object>());
就出错了;错误代码如下:Exception in thread "main" java.lang.ClassCastException: $Proxy0 cannot be cast to java.util.List at cn.heima.test.proxy.ProxyTest.main(ProxyTest.java:12)
getProxy方法
private static Object getProxy(final Object target){
Object proxy=Proxy.newProxyInstance(
target.getClass().getClassLoader()
, target.getClass().getDeclaredClasses()
, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
long beginTime=System.currentTimeMillis();
Object retValue=method.invoke(target, args);
long endTime=System.currentTimeMillis();
System.out.println(method.getName()+"运行时间"+(endTime-beginTime));
return retValue;
}
});
return proxy;
}
}
|
|