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)
{ 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)
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);
}
}
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;public class Ar……
[/Quot 谢谢你,我java刚起步,自学一个月了,嗯,我会加油的