Jdk动态代理

Jdk动态代理

1、创建接口

package com.cn.fb.proxy2;

/**
 * @interface: Calculate
 * @Description: Calculate
 * @Author: liangyongyong
 * @Date: 2022/3/4 11:37
 * @Version: 1.0.0
 */
public interface Calculate {

    public int add(int a, int b);

    public int subtract(int a, int b);

    public int multiply(int a, int b);

    public int divide(int a, int b);
}

2、创建接口实现类

package com.cn.fb.proxy2;

/**
 * @className: MyCalculate
 * @Description: MyCalculate
 * @Author: liangyongyong
 * @Date: 2022/3/4 11:44
 * @Version: 1.0.0
 */
public class MyCalculate implements Calculate {
    @Override
    public int add(int a, int b) {
        return a + b;
    }

    @Override
    public int subtract(int a, int b) {
        return a - b;
    }

    @Override
    public int multiply(int a, int b) {
        return a * b;
    }

    @Override
    public int divide(int a, int b) {
        return a / b;
    }
}

3、创建代理类

package com.cn.fb.proxy2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @className: JdkDynamicProxy
 * @Description: JdkDynamicProxy
 * @Author: liangyongyong
 * @Date: 2022/3/5 9:13
 * @Version: 1.0.0
 */
public class JdkDynamicProxy implements InvocationHandler {

    private Object obj;

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

    /**
     * 产生代理对象
     *
     * @return
     */
    public Object getProxy() {
        // 获取类加载器
        final ClassLoader classLoader = obj.getClass().getClassLoader();
        // 获取接口对象
        final Class<?>[] interfaces = obj.getClass().getInterfaces();
        // 产生代理对象
        final Object o = Proxy.newProxyInstance(classLoader, interfaces, this);
        return o;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        begin();
        // 反射调用方法
        Object invoke = method.invoke(obj, args);
        System.out.println("method.invoke");
        commit();
        return invoke;
    }

    public void begin() {
        System.out.println("=======开启事务=======");
    }

    public void commit() {
        System.out.println("=======提交事务=======");
    }
}

4、Test

package com.cn.fb.proxy2;

/**
 * @className: Test
 * @Description: Test
 * @Author: liangyongyong
 * @Date: 2022/3/4 11:42
 * @Version: 1.0.0
 */
public class Test {
    public static void main(String[] args) {

        MyCalculate myCalculate = new MyCalculate();
        final Calculate calculate = (Calculate) new JdkDynamicProxy(myCalculate).getProxy();
        System.out.println(calculate.add(10, 20));

    }
}

5、执行结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值