在学习动态代理的时候,发现控制台报错
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to...
下面是代码:
public static void main(String[] args) {
//要代理的真实对象
People people = new Teacher();
//代理对象的处理程序,我们将要代理的真实对象传入代理对象的调用处理的构造函数中,最终代理对
象的调用处理程序会调用真实对象的方法。
InvocationHandler handler =new WorkHandler(people);
People proxy = (People)Proxy.newProxyInstance(handler.getClass().getClassLoader(),People.class.getInterfaces(),handler);
System.out.println(proxy.work());
}
提示:People是接口,Teacher是实现类。
看错误信息是在通过Proxy类的newProxyInstance方法创建代理对象的时候出错了。
将People.class.getInterfaces()改为people.getClass().getInterfaces()就可以正常运行了。
总结分析:
newProxyInstance()方法的第二个参数代表的是真实对象实现的接口,
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
返回值Class<?>[]。我们知道类.class == 对象.getClass(),然而这里有个坑,就是People是接口,People.class是获得接口的信息,你再.getInterfaces是获得接口的所有接口。而对象people指向的是Teacher的内存地址,people.getClass().getInterfaces()就是获得Teacher的所有接口,这就说的通了。