Chinaunix

标题: JDK Dynamic Proxy模式的简单范例 [打印本页]

作者: sesutough    时间: 2007-06-06 09:37
标题: JDK Dynamic Proxy模式的简单范例

JDK Dynamic Proxy模式的简单范例
       在JDK1.3版本中引入了Dynamic Proxy的代理机制,通过实现java.lang.reflect.InvocationHandler接口,可以实现拦截需要改写的方法。下面是一个简单范例。
      有下面一个接口TestInterface和它的一个实现TestImpl:

package sample.proxy;



/**//**

* Title:

*

* Description:

*

* Copyright: Copyright (c) 2005

*

* Company:

*

* @author George Hill

* @version 1.0

*/



public interface TestInterface

{


  public String print();


}


package sample.proxy;



/**//**

* Title:

*

* Description:

*

* Copyright: Copyright (c) 2005

*

* Company:

*

* @author George Hill

* @version 1.0

*/



public class TestImpl implements TestInterface

{

  


  public String print()

{

    return "Hello, it's from TestImpl class";

  }

  

}

      下面拦截print方法,调用自己的实现,这需要实现java.lang.reflect.InvocationHandler接口。

package sample.proxy;


import java.lang.reflect.*;



/**//**

* Title:

*

* Description:

*

* Copyright: Copyright (c) 2005

*

* Company:

*

* @author George Hill

* @version 1.0

*/



public class TestHandler implements InvocationHandler

{

  

  TestInterface test;

  


  /**//**

   * 将动态代理绑定到指定的TestInterface

   * @param test TestInterface

   * @return TestInterface 绑定代理后的TestInterface

   */


  public TestInterface bind(TestInterface test)

{

    this.test = test;

   

    TestInterface proxyTest = (TestInterface) Proxy.newProxyInstance(

      test.getClass().getClassLoader(), test.getClass().getInterfaces(), this);

   

    return proxyTest;

  }

  


  /**//**

   * 方法调用拦截器,拦截print方法

   * @param proxy Object

   * @param method Method

   * @param args Object[]

   * @return Object

   * @throws Throwable

   */


  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable

{

    // 如果调用的是print方法,则替换掉


    if ("print".equals(method.getName()))

{

      return "HaHa, It's come from TestHandler";


    } else

{

      return method.invoke(this.test, args);

    }

  }

  

}

      下面是测试用例:

package sample.test;


import junit.framework.*;


import sample.proxy.*;



/**//**

* Title:  

*

* Description:  

*

* Copyright: Copyright (c) 2005

*

* Company:

*

* @author George Hill

* @version 1.0

*/



public class TestDynamicProxy extends TestCase

{

  

  private TestInterface test = null;



  protected void setUp() throws Exception

{

    super.setUp();

    TestHandler handler = new TestHandler();

    // 用handler去生成实例

    test = handler.bind(new TestImpl());

  }



  protected void tearDown() throws Exception

{

    test = null;

    super.tearDown();

  }



  public void testPrint()

{

    System.out.println(test.print());

  }


}

      运行测试用例,可以看到输出的是“HaHa, It's come from TestHandler”。


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/39099/showart_315684.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2