动态代理(java原生动态代理)

简述

java 动态代理是一种基于反射运行时逻辑切入。实现简单,但只作用于接口级别

1. java 动态代理实现步骤简述

  • 创建代理逻辑执行器: InvocationHandler 实例
  • 绑定代理执行逻辑和被代理对象: Proxy.newProxyInstance (返回代理实例时需要强转类型)

2. 动态代理 deamo

package me.proxy;

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

/**
 * 动态代理sample (一码胜千言)
 */
public class Dproxy {

    public static void main(String... args) {
        IBusiness business = new Business();
        ProxyHandler handler = new ProxyHandler(business);

        IBusiness businessProxy = (IBusiness) Proxy.newProxyInstance(
                business.getClass().getClassLoader(), business.getClass().getInterfaces(), handler);

        businessProxy.doBusiness("3", "2", "1", "hello world");

    }

    /**
     * 正常业务接口
     */
    private interface IBusiness {
        String doBusiness(String... args);
    }

    /**
     * 正常业务类
     */
    private static class Business implements IBusiness {
        @Override
        public String doBusiness(String... args) {
            Arrays.stream(args).forEach(e -> System.out.println("do business " + e));
            return args.toString();
        }
    }

    /**
     * 代理逻辑实现
     *
     * 实现代理需要处理的逻辑,包含:
     *
     * 1. 调用前逻辑
     *
     * 2. 调用后逻辑
     *
     * 3. 方法调用姿势逻辑
     */
    private static class ProxyHandler implements InvocationHandler {


        private Object ref;

        public ProxyHandler(Object ref) {
            this.ref = ref;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

            System.out.println("Do something before method");
            Object result = ref == null ? null : method.invoke(ref, args);
            System.out.println("Do something after method");
            return result;
        }
    }

}

样例简单,不必过多解释,想必各位同学对其使用姿势都了然于胸了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值