jdk动态代理

本文介绍了Java中使用CGLIB库实现动态代理的示例。通过ProxyInvocationHandler类,实现了对Host类(实现了Rent接口)的方法调用进行增强,调用前增加了额外的'看看先'操作。动态代理在不修改原有代码的情况下,为对象提供了额外的功能。
摘要由CSDN通过智能技术生成

动态代理,代理的是接口

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();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值