动态代理

来源:互联网 发布:三维模型设计软件 编辑:程序博客网 时间:2024/06/02 03:42

下面是我写的一个ArrayList类的代理,实现和ArrayList中完全相同的功能,并可以计算每个方法运行的时间。

有个问题不是很明白,在main函数中调用getproxy()方法时,返回的为什么不可以是collection的子类ArrayList呢?

public class ProxyDemo2 {@SuppressWarnings("unchecked")public static void main(String[] args) {ArrayList<String> target = new ArrayList<String>();MyAdevice adevice = new MyAdevice();Collection<String> proxy1 =(Collection<String>) getproxy(target, adevice);//ArrayList proxy1 = (ArrayList) getproxy(target, adevice);proxy1.add("sb");proxy1.add("sdfsdfasdfa");proxy1.contains("sb");proxy1.clear();System.out.println(proxy1.size());System.out.println(proxy1.getClass().getName());}public static Object getproxy(final Object target,final Adevice adevice){Object proxy1 = Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {adevice.beforemethod(method);Object obj = method.invoke(target, args);adevice.aftermethod(method);return obj;}});return proxy1;}}


求高手指点!!

0 0
原创粉丝点击