代理

代理

  • 通过代理类完成全部代理

动态代理

关于Proxy.newProxyInstance和InvocationHandler
  • newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)是用于动态生成代理类。
  • 参数:
    1.loader: 类加载器
    2.interfaces:动态代理类需要实现的接口
    3.h:动态代理方法在执行时,会调用h里面的invoke方法去执行。
InvocationHandler
  • 我们可以把InvocationHandler理解为对目标类进行增强,用来处理这些增强逻辑的类。代理类会调用InvocationHandler的invoke()方法,执行增强逻辑。

  • invoke()方法参数:
    1.proxy:就是代理对象,newProxyInstance()方法的返回对象
    2.method:调用的方法
    3.args: 方法中的参数

interface Human{
    String get();
    void eat(String food);
}

class Person implements Human{

    @Override
    public String get() {
        return "我是个正常人";
    }

    @Override
    public void eat(String food) {
        System.out.println("我喜欢吃" + food);
    }
}

class ProxyFactory{

    public static Object getproxyInstance(Object object){
        // java.lang.reflect.Proxy,
        MyInvocationHander myInvocationHander = new MyInvocationHander();
        myInvocationHander.bind(object);
        return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),myInvocationHander);
    }
}
class MyInvocationHander implements InvocationHandler{
    //
    private Object object;

    public void bind(Object object) {
        this.object = object;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return method.invoke(object,args);
    }
}


public class Test2 {
    public static void main(String[] args) {
        Human human = (Human) ProxyFactory.getproxyInstance(new Person());
        human.eat("火锅");
        System.out.println(human.get());

    }
}

静态代理

  • 代理类和被代理类在编译时就已经确定了
interface Factory{
    void production();
}

// 代理类
class proxy implements Factory{
    private Factory factory;

    public proxy(Factory factory) {
        this.factory = factory;
    }

    @Override
    public void production() {
        System.out.println("代理工厂在做准备工作");
        factory.production();
        System.out.println("代理工厂在做收尾工作");
    }
}

// 被代理类
class Nike implements Factory{

    @Override
    public void production() {
        System.out.println("NIKE正在生产");
    }
}

public class Test1 {
    public static void main(String[] args) {
        // 创建被代理类对象
        Nike nike = new Nike();
        // 创建代理类
        proxy proxy = new proxy(nike);

        proxy.production();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

临水而愚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值