关于动态代理,我之前有写过一个很详细很详细的博客,这里不多赘述:
动态代理的代理类是动态生成的,不是直接写好的
动态代理分为两大类:基于接口的动态代理,基于类的动态代理
基于接口的动态代理:JDK动态代理
基于类的动态代理:cglib
1.接口
public interface Rent {
void rent();
}
2.被代理对象实现接口
public class Host implements Rent {
public void rent() {
System.out.println("房东要出租房子");
}
}
3.调用处理程序
//调用处理程序
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target){
this.target=target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(target, args);
return result;
}
}
4.测试类
public class Client {
public static void main(String[] args) {
//被代理对象
Rent rent = new Host();
//调用处理程序对象
MyInvocationHandler myInvocationHandler = new MyInvocationHandler(rent);
//代理对象
Rent proxy = (Rent)Proxy.newProxyInstance(rent.getClass().getClassLoader(),
rent.getClass().getInterfaces(),
myInvocationHandler);
proxy.rent();
}
}