代理模式-ArrayList的动态代理

public class ArrayListProxy {
    public static void main(String[] args) {
        final ArrayList target = new ArrayList();
        List proxy = (List)Proxy.newProxyInstance(
                List. class.getClassLoader(),
                ArrayList. class.getInterfaces(),
                new InvocationHandler(){
                    public Object invoke(Object proxy , Method method, Object[] args)
                            throws Throwable{
                        Long beginTime = System.currentTimeMillis();
                        Thread. sleep(10);
                        Object reVal = method.invoke( target, args);
                        long endTime = System.currentTimeMillis ();

                        System. out.println(method .getName() + " runing time is :" + (endTime - beginTime));
                        return reVal ;
                    }
                });

        proxy.add("测试——1");
        proxy.add("测试——2");
        proxy.add("测试——3");
        proxy.add("测试——4");
        System. out.println(proxy .toString());

    }

}

猜你喜欢

转载自blog.csdn.net/riju4713/article/details/80874830
今日推荐