是用java动态代理的时候
只能对接口的实现类代理吗
如果我有个类extends接口的实现类,还能用动态代理吗

解决方案 »

  1.   

    你有个类extends接口的实现类,则你的这个类也实现了该接口。
    所以可以用动态代理
      

  2.   

    public interface HelloWorld {

    public void SayHello();}public class HelloWorldImpl implements HelloWorld { public void SayHello() {
    System.out.println("hello"); }}public class HelloWorldMSSQL extends HelloWorldImpl {}这是接口、实现类、扩展类
      

  3.   

    这是代理实现类public class HelloWorldHandler implements InvocationHandler {       //要代理的原始对象       private Object objOriginal;       /**        * 构造函数。        * @param obj 要代理的原始对象。        */
           
                 public HelloWorldHandler(Object obj) {              this.objOriginal = obj ;       }
           public Object invoke(Object proxy, Method method, Object[] args)                     throws Throwable {                            Object result ;                      //方法调用之前              doBefore();                      //调用原始对象的方法              result = method.invoke(this.objOriginal ,args);                      //方法调用之后              doAfter();              
                 
                  return result ;       }              private void doBefore() {              System.out.println("before method invoke!");       }              private void doAfter() {              System.out.println("after method invoke!");       }}
      

  4.   

    这是测试HelloWorld hw = new HelloWorldImpl();没问题
    如果是HelloWorld hw =  new HelloWorldMSSQL();就报错java.lang.ClassCastException: $Proxy0 cannot be cast to test.invoke.HelloWorld
    try 
         {
         // HelloWorld hw =  new HelloWorldMSSQL();
     HelloWorld hw = new HelloWorldImpl();
                            InvocationHandler handler = new HelloWorldHandler(hw);        
           
             
             HelloWorld proxy = (HelloWorld) Proxy.newProxyInstance(                        hw.getClass().getClassLoader(),                        hw.getClass().getInterfaces(),                        handler); 
             
             proxy.SayHello();
             
                }
         catch(Exception e)
         {
         e.printStackTrace();
        
         }
      

  5.   

    HelloWorldMSSQL 可以动态代理
    你去实现,出问题帖出来一起解决
      

  6.   

    这样改:
    hw.getClass().getInterfaces()改成hw.getClass().getSuperclass().getInterfaces()
                HelloWorld proxy = (HelloWorld) Proxy.newProxyInstance(hw.getClass().getClassLoader(),
                        hw.getClass().getSuperclass().getInterfaces(), handler);
    我试了,好用。
      

  7.   

    要取得接口,得用接口的实现类来取,所以要先取得父类的Class
      

  8.   

    好像面向接口的可用DynamicProxy,面向抽象类的可用CGLib。