一个简单的例子:
步骤1:创建一个接口IService
package jimmee.cn.edu.zju;
public interface IService {
public boolean getService(String data);
}
步骤2:创建这个接口的实现类ServiceImpl
package jimmee.cn.edu.zju;
public class ServiceImpl implements IService {
public boolean getService(String data) {
if(data.equals("retrieve service"))
return true;
else
return false;
}
}
步骤3:采用JDK的动态代理产生一个拦截器:
package jimmee.cn.edu.zju;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import org.apache.log4j.Logger;
public class ServiceHandler implements InvocationHandler {
Logger log=Logger.getLogger(ServiceHandler.class);
// 在拦截器里需要保存一个被代理的对象的引用
private Object delegate;
// 通过构造方法设置被代理的对象
public ServiceHandler(Object delegate) {
this.delegate = delegate;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
log.info("===============before invoke=========");
// 调用真正的实现
boolean bFlag = (Boolean) method.invoke(delegate, args);
if (bFlag) {
log.info("Get service success!");
} else {
log.info("Get service failed!");
}
log.info("===============after invoke=========");
return method.invoke(delegate, args);
}
}
步骤4:junit测试:
package jimmee.cn.edu.zju;
import java.lang.reflect.Proxy;
import junit.framework.TestCase;
public class ProxyTest extends TestCase {
public void testProxy() {
//实现业务逻辑的类
ServiceImpl service=new ServiceImpl();
//JDK动态代理的拦截器,拦截器里需要保存业务逻辑类的对象
ServiceHandler handler=new ServiceHandler(service);
//创建业务逻辑类的动态代理类
IService proxy=(IService) Proxy.newProxyInstance(service.getClass().getClassLoader(),
service.getClass().getInterfaces(),
handler);
//动态代理类来调用方法
proxy.getService("retrieve service");
}
}
最后:输出结果如下:
2008-03-10 14:41:32,625 INFO [jimmee.cn.edu.zju.ServiceHandler] - ===============before invoke=========
2008-03-10 14:41:32,625 INFO [jimmee.cn.edu.zju.ServiceHandler] - Get service success!
2008-03-10 14:41:32,625 INFO [jimmee.cn.edu.zju.ServiceHandler] - ===============after invoke=========