1,收房租接口
public interface LandLordService {
//收房租
public void rent();
}
2,实现类
public class LandLord implements LandLordService {
public void rent() {
System.out.println("房东亲自收入房租");
}
}
JDK动态代理
public class JdkProxy implements InvocationHandler {
//要代理增强的对象
private Object instance;
public JdkProxy(Object instance) {
this.instance = instance;
}
//使用此方法进行动态代理,使用此方法进行原方法的扩展
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("JDK动态代理开始");
Object invoke = method.invoke(instance, args);
System.out.println("JDK动态代理结束");
return invoke;
}
}
测试方法
public class JdkProxyTest {
public static void main(String[] args){
LandLordService landLord = new LandLord();
//房东收房租
landLord.rent();
JdkProxy jdkProxy = new JdkProxy(landLord);
LandLordService landLordProxy = ( LandLordService )Proxy.newProxyInstance(LandLord.class.getClassLoader(), landLord.getClass().getInterfaces(), jdkProxy);
//动态代理类进行收房租
landLordProxy.rent();
}
}
测试结果
房东亲自收入房租
JDK动态代理开始
房东亲自收入房租
JDK动态代理结束
CgLib动态代理
public class CgLibProxy implements MethodInterceptor {
//要代理增强的对象
private Object instance;
public CgLibProxy(Object instance) {
this.instance = instance;
}
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("CgLib动态代理开始");
Object invoke = method.invoke(instance, objects);
System.out.println("CgLib动态代理结束");
return invoke;
}
}
测试方法
public class CglibProxyTest {
public static void main(String[] args){
LandLord landLord = new LandLord();
landLord.rent();//房东收房租
CgLibProxy cgLibProxy = new CgLibProxy(landLord);
LandLord landLordProxy = (LandLord)Enhancer.create(LandLord.class, cgLibProxy);
landLordProxy.rent();//动态代理收房租
}
}
测试结论
Connected to the target VM, address: '127.0.0.1:61048', transport: 'socket'
房东亲自收入房租
Disconnected from the target VM, address: '127.0.0.1:61048', transport: 'socket'
CgLib动态代理开始
房东亲自收入房租
CgLib动态代理结束
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
Process finished with exit code 0