动态代理
之前学习过静态代理,发现有个缺点,每当需要代理一个类就需要创建与之相当的代理类,极大的增加了代码量。现在通过动态代理,可以通过极少的代码量实现所要的功能
动态代理与静态代理拥有一样的角色:
抽象角色
、真实角色
、代理角色
首先定义一个抽象角色
public interface Rent {
public void rent();
}
再定义一个真实角色
public class Landlord implements Rent{
@Override
public void rent() {
System.out.println("出租房屋");
}
}
最后创建代理类
public class ProxyInvocationHandler implements InvocationHandler{
Rent rent;//抽象代理类
public void setRent(Rent rent) {
this.rent = rent;
}
/*获取代理对象*/
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), rent.getClass().getInterfaces(), this);
}
/*实现步骤*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(rent, args);
}
}
测试代码
public static void main(String[] args) {
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
proxyInvocationHandler.setRent(new Landlord());
Rent rent = (Rent) proxyInvocationHandler.getProxy();
rent.rent();
}
测试结果如下
出租房屋
将上面的动态代理类修改一下,成为一个可以复用的类似工具类的类
public class ProxyInvocationHandler implements InvocationHandler{
Object target;
public void setRent(Object target) {
this.target = target;
}
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(target, args);
}
}