当前位置: 代码迷 >> J2SE >> 关于动态代理模式,求解!该怎么解决
  详细解决方案

关于动态代理模式,求解!该怎么解决

热度:85   发布时间:2016-04-24 01:17:50.0
关于动态代理模式,求解!!!
public class ArrayListTest implements InvocationHandler
{

private Object target;

public ArrayListTest()
{

}

public ArrayListTest(Object target)
{
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
return method.invoke(target, args);
}

public static Object factory(Object target)
{
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfa(), new ArrayListListTest());
}

public static void main(String[] args)
{
List arraylist = (List)factory(new ArrayList());

arraylist.add("hello");

System.out.println(arraylist);
}
}


为什么运行结果后出现这个
Exception in thread "main" java.lang.ClassCastException: $Proxy0 cannot be cast to java.awt.List
at com.xieyuzhi.Proxy.LinkedListTest.main(LinkedListTest.java:37)


------解决方案--------------------
lz仍需努力~

Java code
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 ArrayListTest implements InvocationHandler {    private Object target;    public ArrayListTest() {    }    public ArrayListTest(Object target) {        this.target = target;    }    public Object invoke(Object proxy, Method method, Object[] args)            throws Throwable {        return method.invoke(target, args);    }    public static Object factory(Object target) {        ArrayListTest alt = new ArrayListTest(target);        return Proxy.newProxyInstance(target.getClass().getClassLoader(),                target.getClass().getInterfaces(), alt);    }    public static void main(String[] args) {        @SuppressWarnings("unchecked")        List<String> arraylist = (List<String>) factory(new ArrayList<String>());        arraylist.add("hello");        System.out.println(arraylist);    }}
  相关解决方案