廢話不多說了肺素,先來看一下JDK的動態(tài)是怎么用的壮锻。
package dynamic.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 實現(xiàn)自己的InvocationHandler
* @author zyb
* @since 2012-8-9
*
*/
public class MyInvocationHandler implements InvocationHandler {
// 目標(biāo)對象
private Object target;
/**
* 構(gòu)造方法
* @param target 目標(biāo)對象
*/
public MyInvocationHandler(Object target) {
super();
this.target = target;
}
/**
* 執(zhí)行目標(biāo)對象的方法
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 在目標(biāo)對象的方法執(zhí)行之前簡單的打印一下
System.out.println("------------------before------------------");
// 執(zhí)行目標(biāo)對象的方法
Object result = method.invoke(target, args);
// 在目標(biāo)對象的方法執(zhí)行之后簡單的打印一下
System.out.println("-------------------after------------------");
return result;
}
/**
* 獲取目標(biāo)對象的代理對象
* @return 代理對象
*/
public Object getProxy() {
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
target.getClass().getInterfaces(), this);
}
}
package dynamic.proxy;
/**
* 目標(biāo)對象實現(xiàn)的接口,用JDK來生成代理對象一定要實現(xiàn)一個接口
* @author zyb
* @since 2012-8-9
*
*/
public interface UserService {
/**
* 目標(biāo)方法
*/
public abstract void add();
}
package dynamic.proxy;
/**
* 目標(biāo)對象
* @author zyb
* @since 2012-8-9
*
*/
public class UserServiceImpl implements UserService {
/* (non-Javadoc)
* @see dynamic.proxy.UserService#add()
*/
public void add() {
System.out.println("--------------------add---------------");
}
}
package dynamic.proxy;
import org.junit.Test;
/**
* 動態(tài)代理測試類
* @author zyb
* @since 2012-8-9
*
*/
public class ProxyTest {
@Test
public void testProxy() throws Throwable {
// 實例化目標(biāo)對象
UserService userService = new UserServiceImpl();
// 實例化InvocationHandler
MyInvocationHandler invocationHandler = new MyInvocationHandler(userService);
// 根據(jù)目標(biāo)對象生成代理對象
UserService proxy = (UserService) invocationHandler.getProxy();
// 調(diào)用代理對象的方法
proxy.add();
}
}