java的jdk动态代理和cglib动态代理

  1. jdk动态代理   
/**
 * @ClassName:
 * @Description: Jdk的动态代理:代理对象跟目标对象要实现相同接口,拦截器必须实现InvocationHandler接口
 * @yanchan [280822963@qq.com]
 * @date 2018/4/11 0011 14:11
 */
public class IInvocationHandler implements InvocationHandler {

    private Object obj;

    public IInvocationHandler(Object obj) {
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before");
        method.invoke(obj, args);
        System.out.println("after");
        return null;
    }

    public static void main(String[] args) {
        Man man = new Man();
        IInvocationHandler var = new IInvocationHandler(man);
        Person proxyInstance = (Person) Proxy.newProxyInstance(man.getClass().getClassLoader(), man.getClass().getInterfaces(), var);
        proxyInstance.eat();

    }
}

 2.cglib动态代理

/**
 * @ClassName:
 * @Description: cglib 动态代理: 代理对象是目标对象的子类 ,拦截器必须实现MethodInterceptor接口
 * @yanchan [280822963@qq.com]
 * @date 2018/4/11 0011 12:09
 */
public class IMethodInterceptor implements MethodInterceptor {

    private Object targetObj;

    public IMethodInterceptor(Object targetObj) {
        this.targetObj = targetObj;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("before");
        method.invoke(targetObj, objects);
        System.out.println("after");
        return null;
    }

    public static void main(String[] args) {
        IMethodInterceptor interceptor = new IMethodInterceptor(new Person());
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(interceptor);
        enhancer.setSuperclass(Person.class);
        Person proxyObj = (Person) enhancer.create();
        proxyObj.eat();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值