首页 > 代码库 > 对list代理扩展功能

对list代理扩展功能

package 动态代理扩展List;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public class ListPro {

    public static void main(String[] args) {

        final List<Object> list = new ArrayList<Object>();
        // 对list代理

        Object lis = Proxy.newProxyInstance(ListPro.class.getClassLoader(),

        new Class[] { List.class }, new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                // 显示参数
                if (method.getName().equals("add")) {

                    System.err.println("参数" + args[0]);

                }
                // diaoyong
                return method.invoke(list, args);
            }
        });
        // 转换

        List<Object> l = (List<Object>) lis;
        l.add("kk");
        System.err.println("size:" + l.size() + "," + list.size());
        System.err.println("-----------");
        list.add("xx");
        System.err.println("size2:" + l.size() + "," + list.size());
        System.err.println("========");

        for (Object ls : l) {
            System.err.println(ls);

        }
    }
}