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

/**/
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @author George Hill
* @version 1.0
*/


public
interface
TestInterface
{
public String print();
}
package sample.proxy;

/**/
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @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.
*
;

/**/
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @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.
*
;

/**/
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @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”。
本文介绍JDK1.3引入的DynamicProxy机制,并通过一个简单案例演示如何使用该机制来拦截并修改方法调用。案例包括定义接口、实现类及自定义InvocationHandler。
4171

被折叠的 条评论
为什么被折叠?



