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

来源:互联网 发布:淘宝联盟登上去不能用 编辑:程序博客网 时间:2024/06/05 18:30

简述

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

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

0 0