动态代理
动态代理是指通过jvm反射机制,让一个类代替另一个类做需要做的事。
以小明要给班花小红送花,找小王代理送花为例子
事件接口
public interface IGiveSomething {
public void giveFlower();
}
事件接口实现类和其他类
班花类
/**
* 班花类
*/
public class ClassFlower {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ClassFlower() {
}
public ClassFlower(String name) {
this.name = name;
}
}
送花人类
public class YuanZhong implements IGiveSomething{
//送花人的名字
private String name;
//要送给哪个班花
private ClassFlower classFlower;
public YuanZhong() {
}
public YuanZhong(String name) {
this.name = name;
}
//设置送花人名字
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ClassFlower getClassFlower() {
return classFlower;
}
//设置班花
public void setClassFlower(ClassFlower classFlower) {
this.classFlower = classFlower;
}
//送花事件
@Override
public void giveFlower() {
System.out.println(name+"给 "+classFlower.getName()+" 999朵花");
}
}
代理类
public class DyProxy implements InvocationHandler {
public DyProxy() {
}
public DyProxy(Object object) {
this.object = object;
}
//帮谁代理
private Object object;
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("运行前的时间"+ LocalDateTime.now().toString());
System.out.println("proxy "+proxy.getClass().getName()+" , method "+method+" , args "+args);
Object invoke = method.invoke(object, args);
System.out.println("运行后的时间"+ LocalDateTime.now().toString());
return invoke;
}
}
测试
public class ProxyTest {
public static void main(String[] args) {
//定义班花 小红
ClassFlower classFlower = new ClassFlower("小红");
//定义送花人 小明
YuanZhong yuanZhong = new YuanZhong("小明");
//设置 小明 要送花给班花 小红
yuanZhong.setClassFlower(classFlower);
//定义代理人
DyProxy dyProxy = new DyProxy();
//设置帮小明代理
dyProxy.setObject(yuanZhong);
//第一个参数:事件的接口 IGiveSomething.class.getClassLoader()
//第二个参数:事件接口的实现类 yuanZhong.getClass().getInterfaces()
//第三个参数:代理类 dyProxy
IGiveSomething iGiveSomething = (IGiveSomething) Proxy.newProxyInstance(IGiveSomething.class.getClassLoader(), yuanZhong.getClass().getInterfaces(), dyProxy);
//执行代理事件
iGiveSomething.giveFlower();
}
}