动态代理,代理的是接口
package com.zq;
/**
* @author daxia @create 2021-10-20 21:52
*/
public interface Rent {
void rent();
}
package com.zq;
/**
* @author daxia @create 2021-10-20 21:47
*/
public class Host implements Rent{
public void rent() {
System.out.println("房东出租房子");
}
}
package com.zq;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;
import java.lang.reflect.Method;
/**
* @author daxia @create 2021-10-20 21:51
*/
public class ProxyInvocationHandler implements
InvocationHandler {
//向调用处理程序注入北欧代理的目标对象(房东--房东不想干活了)
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//通过Proxy获取代理对象
public Object getProxyInstance(){
//返回指定接口的代理类的实例,该接口将方法调用分派给指定的 调用处理程序 (InvocationHandler,this继承InvocationHandler,使用本类即可)。
//通过this(调用程序管理器)来调用Invoke放来掉欧调用代理方法
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//该处可以写增加方法
see();
return method.invoke(target,args);
}
public void see(){
System.out.println("看看先");
}
}
package com.zq;
/**
* @author daxia @create 2021-10-20 21:51
*/
public class Client {
public static void main(String[] args) {
//目标被代理角色(房东)
Host host = new Host();
//创建调用程序处理器
ProxyInvocationHandler ProxyInvocationHandler = new ProxyInvocationHandler();
//调用程序处理注入目标对象(被代理对象)
ProxyInvocationHandler.setTarget(host);
//获取动态代理角色,Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
//注入的目标对象的接口target.getClass().getInterfaces() (Rent),返回也是接口
Rent proxyInstance = (Rent) ProxyInvocationHandler.getProxyInstance();
//调用目标方法
proxyInstance.rent();
}
}