动态代理是指客户通过代理类来调用其他对象的方法,并且是在程序运行时根据需要创建目标类的代理对象。
原理:
使用一个代理将对象包装起来,然后用该代理对象取代原对象,任何对原始对象的调用都要通过dialing,代理对象决定是否以及何时将方法调用转到原始对象上。
生活中海外代购其实就用到了代理,你可能不方便出国,但是代购可以,最终帮你完成购买行为。
以代购为例子完成静态代理
package com.jikedaquan.reflection;
//购买接口(约定)
interface Buy{
void buyProduct();
}
//被代理的
class Customer implements Buy{
@Override
public void buyProduct() {
System.out.println("购买商品");
}
}
//代理
class ProxyBuy implements Buy{
private Customer customer;
public ProxyBuy(Customer customer) {
this.customer=customer;
}
@Override
public void buyProduct() {
System.out.println("代理:出国");
//被代理的对象的行为
customer.buyProduct();
System.out.println("代理:回国");
}
}
public class TestStaticProxy {
public static void main(String[] args) {
Customer customer=new Customer();
Pr,oxyBuy proxyBuy=new ProxyBuy(customer);
p,roxyBuy.buyProduct();
}
}
那么动态代理意味着不能只代理 Customer 类的行为,还可以代理其他类的行为
package com.jikedaquan.reflection;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//工厂接口
interface Factory{
void product();
}
//电脑工厂
class ComputerFactory implements Factory{
@Override
public void product() {
System.out.println("生产电脑");
}
}
//动态代理处理器
class MyInvocationHandler implements InvocationHandler{
//要被代理的对象
private Object proxyObj;
//产生代理对象
public Object bind(Object proxyObj) {
this.proxyObj=proxyObj;
return Proxy.newProxyInstance(
proxyObj.getClass().getClassLoader(),
proxyObj.getClass().getInterfaces(),
this
);
}
//代理对象实际执行的方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理:收收费");
Object result=method.invoke(proxyObj, args);
System.out.println("代理:代理完成");
return result;
}
}
public class TestDynamicProxy {
public static void main(String[] args) {
//创建代理对象生产器
MyInvocationHandler invocationHandler=new MyInvocationHandler();
//创建要被代理的对象
ComputerFactory computerFactory=new ComputerFactory();
//生产代理对象
Object factoryProxy=invocationHandler.bind(computerFactory);
Factory factory=(Factory) factoryProxy;
factory.product();
//创建另一个要被代理的对象(上个示例静态代理的对象和接口)
Customer customer=new Customer();
//生产代理对象
Object buyProxy=invocationHandler.bind(customer);
Buy buy=(Buy) buyProxy;
buy.buyProduct();
}
}
在 main 方法中,创建了一个 MyInvocationHandler 对象,通过 bind 方法可以传入任意要被代理的对象,实现了动态。
重点来了,拿好小本子笔记。。。。狘/p>
实现动态代理的步骤:
1.创建要被代理的类的接口
2.创建要被代理的类实现类
3.创建代理对象处理器(MyInvocationHandler),实现 InvocationHandler 接口
4.编写生产代理对象的方法,方法内调用 Proxy.newInstance() 方法,返回代理对象
5.重写 InvocationHandler 的 invoke 方法
6.测试:创建代理对象生产器,生产代理对象
当前文章:http://www.carinsurancequoteny.com/81sw06r4/46d795_722854.html
发布时间:2018-11-22 06:02:22
www.777729.com www.4043b.com 香港黄大仙一句解一肖 管家婆中特彩图 www.336621.com www.333003.com 管家婆挂牌官网 王中王论坛 香港最准一肖中特公开 www.4455tk.com