- import java.lang.reflect.*;
- import java.util.*;
- public class ProxyDemo {
- public static void main(String[] args) {
-
- Collection<Integer> proxy = getProxy(Integer.class);
- Collection<String> proxy2 = getProxy(String.class);
- proxy.add(11);
- proxy.add(22);
- proxy2.add("hahahahahahahahahaha");
-
- System.out.println(proxy);
- System.out.println(proxy2);
-
- }
- @SuppressWarnings("unchecked")
- public static <E> ArrayList<E> getProxy(Class<E> eType){
-
- ArrayList<E> al = (ArrayList<E>) Proxy.newProxyInstance(
- ArrayList.class.getClassLoader(), //这里是什么意思,用类加载器加载代理类吗?
- ArrayList.class.getInterfaces(), //这里也不懂
- new InvocationHandler() {
- ArrayList<E> list = new ArrayList<E>();
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- Object reval = method.invoke(list, args);
- return reval;
- }
- });
- return (ArrayList<E>)al;
- }
- }
复制代码 注释里的2个问题。
还有这个程序运行出错啊,说什么类型转换失败。这个怎么办,求解答!
|
|