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); }}