cglib的子实现类的代理

//的类

import com.fhw.proxy.IProducer;

public class Producer implements IProducer {
/销售 与生产/
public void saleProducer(float money) {
System.out.println(“cglib 代理的:销售 产品的钱”+money);
}

/**
 *
 * @param money
 */
public void afterService(float money) {

    System.out.println("销后服务,的钱"+money);
}

}

//测试类

public class Client {
public static void main(String[] args) {
//当匿名对象访问 外部成员的时候 外部成员是最终的 final 的
final Producer producer = new Producer();
/*
* 动态代理 : 特点 : 字节码 随用 随创建 随用随加载
* 作用 : 不修改代码 对方法增强
* 分类: 1:基于 接口的
* 2:基于 子类的
* --------------
* 基于子实现类 的 动态代理
* 涉及的类 : Enhancer
* —>提供:cglib官方
* 创建代理对象—用 Enhancer 的create 类当中 的
* 要求: 被代理对象不是 最终类—要有子类
* 看源码:调用的create()重载方法
* 参数有:Class type CallBack callback
* class:字节码的 类型
被代理对象 字节码
* 代理对象 和 被代理对象使用相同的字节码
* (写的 是 :要代理对象的…getClass().getClassLoader())
* 子类的方式是不行任何 的接口的 所以没有容器的必要
* Callback : 调用处理: 如何代理 增强的
MethodInterceptor:该接口的 子接口 实现类 就是匿名类
谁用谁写
intercept():拦截方法
* /
/加载类与子实现类/
Producer proxyProducer=(Producer)Enhancer.create(producer.getClass(), new MethodInterceptor() {
/
*
* 执行执行任何被代理对象 的任何方法 都会经过该方法
* @param o
* @param method
* @param objects
* 以上三个参数和 与 基于接口 的动态代理invock 的参数是一致的
* @param methodProxy: 执行的方法 的代理对象
* @return
* @throws Throwable
/
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
//提供增强的 代码—>获取方法执行的参数
Object returnValue=null;
Float money=(Float)objects[0] ;//j=就一个index 0 的args
//判断挂起方法的是不是 销售
if (“saleProducer”.equals(method.getName())){
returnValue=method.invoke(producer,money
0.8f);//要代理的对象
}
//return method.invoke(producer,
return returnValue;//要代理的对象
}
});

打印的测试 日志

WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
销售 产品的钱9600.0

Process finished with exit code 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值