JDK动态代理
1、被代理的类必须实现一个接口
2、创建代理对象的时候,用JDK代理需要实现InvocationHandler
3、代理过程在invoke中实现
接口
public interface LandlordService {
void rentingPay(String name);
}
被代理对象
public class Landlord implements LandlordService{
/****
* @param name
*/
@Override
public void rentingPay(String name){
System.out.println(name+" 来交租!");
}
}
代理对象
public class QFangProxy implements InvocationHandler{
private Object instance;
public QFangProxy(Object instance) {
this.instance = instance;
}
/****
* 代理过程
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
args[0] = "中介QFang带领租户"+args[0];
Object result = method.invoke(instance, args);
return result;
}
}
测试
public class JdkProxyTest {
public static void main(String[] args) {
//给QFang产生代理
LandlordService landlordService = new Landlord();
QFangProxy proxy = new QFangProxy(landlordService);
LandlordService landlordServiceProxy = (LandlordService)
Proxy.newProxyInstance(LandlordService.class.getClassLoader(), new Class[]
{LandlordService.class}, proxy);
//通过代理对象调用Landlord对象的方法
landlordServiceProxy.rentingPay("王五");
}
}
CGLib动态代理
要点:
1、代理过程可以实现MethodInterceptor(Callback)接口中的invoke来实现
2、通过Enhancer来创建代理对象
被代理类基于上方提供
代理类
public class SFangProxy implements MethodInterceptor {
private Object instance;
public SFangProxy(Object instance) {
this.instance = instance;
} /
***
* 代理过程
* @throws Throwable
*/
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)throws Throwable {
args[0]="S房网带租户"+args[0];
return method.invoke(instance,args);
}
}
基于接口
public class CGLibProxyTest {
public static void main(String[] args) {
//给QFang产生代理
LandlordService landlordService = new Landlord();
SFangProxy proxy = new SFangProxy(landlordService);
LandlordService landlordServiceProxy = (LandlordService)
Enhancer.create(LandlordService.class,proxy);
//通过代理对象调用Landlord对象的方法
landlordServiceProxy.rentingPay("王五");
}
}
基于类
public class CGLibProxyTest {
public static void main(String[] args) {
//给指定对象创建代理
Landlord landlord = new Landlord();
//1.被代理的对象字节码
//2.代理的过程实现,需要实现接口MethodInterceptor->Callback
Landlord proxyLandlord = (Landlord) Enhancer.create(Landlord.class,new SFang(landlord));
proxyLandlord.pay("赵六");
}
}