日期:2014-05-20  浏览次数:20739 次

求助,动态代理模式的困惑
小弟最近在看动态代理的时候觉得有些奇怪

package   bbb;

import   java.lang.reflect.*;
import   java.util.*;

public   class   Test   implements   java.lang.reflect.InvocationHandler   {
private   Object   ob;

public   Test(Object   oo)   {
ob   =   oo;
}

public   static   Object   factory(Object   oo)   {
Class   cls   =   oo.getClass();
Object   o   =   Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),new   Test(oo));
// System.out.println(o.getClass());   //此处的对像是Proxy?????
return   o;
}

public   Object   invoke(Object   proxy,   Method   method,   Object[]   args)   throws   Throwable  
{
//System.out.println( "我让代理了 ");
Object   o   =   method.invoke(ob,args);

return   o;
}

public   static   void   main(String   args[])   throws   Exception   {
        Object   oo   =   factory(new   TTT());   //如果factory是Proxy,如何转型成Good?
        System.out.println(oo.getClass().getName());
        Proxy   v   =   (Proxy)oo;
        System.out.println(v);
        Good   f   =   (Good)v;
        f.ff();
        }
}

interface   Good   {
void   ff();
}

class   TTT   implements   Good   {
public   void   ff()   {}
}



我的问题是一个类并没有实现一个接口却能被转型成那个接口请问这是如何实现的???  


------解决方案--------------------
你说的是哪一个类 是不是 Good f = (Good)v;

这个代理对象肯定实现了Good接口

Object o = Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),new Test(oo));

这里就可以看到创建这个对象的时候 通过cls.getInterfaces(), 把Good接口传给他了
------解决方案--------------------
如果一个类没有实现接口却强制转换类型的话,就会抛出转换异常ClassCastException