熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

java動態代理Dynamic Proxy

2022-06-13   來源: Java核心技術 

  被代理對象的接口:

   package testdynamicproxy;

  

   public interface TargetInterface {

       public void SayHello();

       public int sum(int a int b);

   }

  被代理的對象:

   package testdynamicproxy;

  

   public class Target implements TargetInterface {

  

       public void SayHello(){

           Systemoutprintln(Hello);

       }

       public int sum(int a int b) {

           return a+b;

       }

   }

  InvocationHandler包裝:

   package testdynamicproxy;

  

   import javalangreflectInvocationHandler;

   import javalangreflectMethod;

  

   public class TargetInvocationHandler implements InvocationHandler {

  

       private Object object;

       public TargetInvocationHandler(Object obj){

           thisobject=obj;

       }

  

       public Object invoke(Object proxy Method method Object[] args)

       throws Throwable

       {

           doBefore();

           Object result = methodinvoke(object args);

           doAfter();

           return result;

       }

  

       public void doBefore(){

           Systemoutprintln(do before);

       }

  

       public void doAfter(){

           Systemoutprintln(do after);

       }

   }

  測試類:

   package testdynamicproxy;

  

   import javalangreflectProxy;

  

   public class TestDynamicProxy {

  

       /**

        * @param args

        */

       public static void main(String[] args) {

           Target t=new Target();

           TargetInvocationHandler handler=new TargetInvocationHandler(t);

  

           TargetInterface proxy = (TargetInterface) ProxynewProxyInstance(

                   tgetClass()getClassLoader()

                   tgetClass()getInterfaces()

                   handler);

  

           proxySayHello();

  

           int b=proxysum( );

           Systemoutprintln(b);

       }

  

   }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26689.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.