jdk动态代理

本文对JDK动态代理进行代码分析,介绍了CalculatorService类及main方法各步骤执行结果。详细解释了JDK动态代理生成代理类、对象及执行方法的过程。还总结了JDK动态代理的特点,同时介绍了CGLib动态代理,最后对比了两者区别,JDK基于接口,CGLib基于类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码分析:

package com.jd.test;

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

import com.jd.calculator.CalculatorService;
import com.jd.calculator.ICalculatorService;

public class Test {
	//动态(程序运行时实现和目标类相同接口的java类)代理()
	CalculatorService calculatorService;
	
	public Test(CalculatorService calculatorService) {
		this.calculatorService = calculatorService;
	}
	
	InvocationHandler h = new InvocationHandler() {
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			System.out.println(proxy.getClass().getName());
			System.out.println(method.getDeclaringClass().getName());
			String name = method.getName();
			System.out.println(this.getClass().getName()+":The "+name+" method begins.");
			System.out.println(this.getClass().getName()+":Parameters of the "+name+" method: ["+args[0]+","+args[1]+"]");
			Object result = method.invoke(calculatorService, args);//目标方法
			System.out.println(this.getClass().getName()+":Result of the "+name+" method:"+result);
			System.out.println(this.getClass().getName()+":The "+name+" method ends.");
			return result;
		}
	};
	
	public Object get() {
		return Proxy.newProxyInstance(Test.class.getClassLoader(), new Class[] {ICalculatorService.class}, h);//产生一个动态class类,并返回一个动态对象
	}

	public static void main(String[] args) {
		System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
		Test test = new Test(new CalculatorService());
		ICalculatorService calculatorService = (ICalculatorService) test.get();//获取代理对象
		System.out.println(calculatorService.getClass().getName());
		int result = calculatorService.add(1, 1);
		System.out.println("-->"+result);
	}
}

前提:

    CalculatorService中有加减乘除四个方法,分别是public int add(int a, int b),public int sub(int a, int b),

                                                                            public int mul(int a, int b),public int div(int a, int b),

    CalculatorService实现ICalculatorService接口

    main方法:(先大致说明每一步执行后得到的结果,下面再进行详细解释)

        第一行:生成代理类形成的class文件

        第二行:为上面声明的calculatorService赋值

        第三行:执行Test中的get()方法,产生一个动态代理类(下面简称代理类),并且返回一个动态类的动态对象

        第四行:(这行是为了验证,后面说明)

        第五行:获得执行add方法后的结果

        第六行:输出结果

    各行结果解释:

        第一行: JDK动态代理生成class文件:

                         System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

                     CGLib生成class文件:

                         System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "E://tmp");

        第二行:这个很容易理解,调用了Test类的有参构造方法Test(CalculatorService calculatorService),为calculatorService赋值

        第三行:调用了无参方法get(),该方法中又调用了newProxyInstance()方法,第一个参数中的getClassLoader()方法返回一个ClassLoader类型的变量,第二个参数是接口的class对象,第三个参数是InvocationHandler匿名内部类对象,进入newProxyInstance()方法有以下代码;

public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        Objects.requireNonNull(h);

        final Class<?>[] intfs = interfaces.clone();
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        /*
         * Look up or generate the designated proxy class.
         */
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }

            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            return cons.newInstance(new Object[]{h});
        } catch (IllegalAccessException|InstantiationException e) {
            throw new InternalError(e.toString(), e);
        } catch (InvocationTargetException e) {
            Throwable t = e.getCause();
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new InternalError(t.toString(), t);
            }
        } catch (NoSuchMethodException e) {
            throw new InternalError(e.toString(), e);
        }
    }

          在这个方法中,有几个地方需要明白:

             ①:final Class<?>[] intfs = interfaces.clone();        clone()拷贝一个interfaces对象,即向newProxyInstance()传入的ICalculatorService的class对象

             ②:Class<?> cl = getProxyClass0(loader, intfs);     生成指定接口ICalculatorService的代理类,并获得代理类的class对象;(另外,在getProxyClass0(loader, intfs)方法里,JDK对代理进行了缓存,如果已经存在相应的代理类,直接返回,否则才会通过ProxyClassFactory来创建代理)

             ③:final Constructor<?> cons = cl.getConstructor(constructorParams); 获取代理类cl的构造方法,constructorParams类型是对象数组。

             ④:return cons.newInstance(new Object[]{h});  创建一个代理类对象并返回,并且调用其中的有参构造方法$Proxy0(InvocationHandler invocationhandler),参数h为传入的InvocationHandler匿名内部类对象

              在这有一点需要说明,通过反编译器,可以得到编译后的java代码表示的class文件,下面是为了容易理解,删去部分代码后得到的:

package com.sun.proxy;

import com.jd.calculator.ICalculatorService;
import java.lang.reflect.*;

public final class $Proxy0 extends Proxy
    implements ICalculatorService
{

    public $Proxy0(InvocationHandler invocationhandler)
    {
        super(invocationhandler);
    }


    public final int add(int i, int j)
    {
        try
        {
            return (
            		(Integer)super.h.invoke(this, m3, new Object[] {Integer.valueOf(i), Integer.valueOf(j)
            ).intValue();
        }
        catch(Exception(throwable);
        }
    }
   
    private static Method m3;

    static 
    {
        m3 = Class.forName("com.jd.calculator.ICalculatorService").getMethod("add", new Class[] {Integer.TYPE, Integer.TYPE});
    }
}

                ④中执行的有参构造方法,就是这个类中的有参构造方法;这个构造方法为父类Proxy中的h赋值,这一步执行完毕之后,Test中main方法中的第三行代码执行完毕,得到了一个代理对象

protected InvocationHandler h;

    /**
     * Prohibits instantiation.
     */
    private Proxy() {
    }

    /**
     * Constructs a new {@code Proxy} instance from a subclass
     * (typically, a dynamic proxy class) with the specified value
     * for its invocation handler.
     *
     * @param  h the invocation handler for this proxy instance
     *
     * @throws NullPointerException if the given invocation handler, {@code h},
     *         is {@code null}.
     */
    protected Proxy(InvocationHandler h) {
        Objects.requireNonNull(h);
        this.h = h;
    }

        第四行:这一步是为了验证,得到的代理对象和上面invoke()中传入的proxy,是相同的

        第五行:calculatorService的值是代理对象,所以执行代理类中的add方法,

package com.sun.proxy;

import com.jd.calculator.ICalculatorService;
import java.lang.reflect.*;

public final class $Proxy0 extends Proxy
    implements ICalculatorService
{

    public $Proxy0(InvocationHandler invocationhandler)
    {
        super(invocationhandler);
    }


    public final int add(int i, int j)
    {
        try
        {
            return (
            		(Integer)super.h.invoke(this, m3, new Object[] {Integer.valueOf(i), Integer.valueOf(j)
            ).intValue();
        }
        catch(Exception(throwable);
        }
    }
   
    private static Method m3;

    static 
    {
        m3 = Class.forName("com.jd.calculator.ICalculatorService").getMethod("add", new Class[] {Integer.TYPE, Integer.TYPE});
    }
}

                    add方法中(Integer)super.h.invoke(this, m3, new Object[] {Integer.valueOf(i), Integer.valueOf(j)

                   由于上面④中调用有参构造方法$Proxy0(InvocationHandler invocationhandler),给这个类的父类Proxy中的invocationHandler赋的值为invocationHandler对象,所以在这里super.h是invocationHandler ,  super.h.invoke相当于invocationHandler.invoke,也就是调用Test.java匿名内部类invocationHandler中的invoke()方法。下面对传入的参数进行解释:

                           this就是调用invoke方法的对象,calculatorService的值,也就是代理对象

                           这里的method就是m3,也就是代码最下面静态代码块中加载的ICalculatorService接口中的add方法

                           向add中传入的常量值i,j    在这里是先将二者转换成了Integer类型;

InvocationHandler h = new InvocationHandler() {
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			System.out.println(proxy.getClass().getName());
			System.out.println(method.getDeclaringClass().getName());
			String name = method.getName();
			System.out.println(this.getClass().getName()+":The "+name+" method begins.");
			System.out.println(this.getClass().getName()+":Parameters of the "+name+" method: ["+args[0]+","+args[1]+"]");
			Object result = method.invoke(calculatorService, args);//目标方法
			System.out.println(this.getClass().getName()+":Result of the "+name+" method:"+result);
			System.out.println(this.getClass().getName()+":The "+name+" method ends.");
			return result;
		}
	};

                    在这个匿名内部类的invoke方法中,method.invoke(calculatorService, args);这个相当于调用的calculatorService中的add方法,将得到的结果返回给result;匿名内部类的invoke方法执行结束,代理类中的super.h.invoke(this, m3, new Object[] {Integer.valueOf(i), Integer.valueOf(j);这部分代码执行结束。由于匿名内部类的invoke方法是Object类,所以要将其转换成Integer类,再调用intValue(),将其转换成int类型。至此代理类中的add方法结束,并将结果返回给Test中main方法第五行里面的result,Test中main方法第五行代码也执行结束。

      第六行:输出得到的结果。

总结:

    1)Interface:对于JDK proxy,业务类是需要一个Interface的,这是一个缺陷

    2)Proxy,Proxy 类是动态产生的,这个类在调用Proxy.newProxyInstance(targetCls.getClassLoader, targetCls.getInterface,InvocationHander)之后,会产生一个Proxy类的实例。实际上这个Proxy类也是存在的,不仅仅是类的实例。这个Proxy类可以保存到硬盘上。

    3) Method:对于业务委托类的每个方法,现在Proxy类里面都不用静态显示出来

    4) InvocationHandler: 这个类在业务委托类执行时,会先调用invoke方法。invoke方法再执行相应的代理操作,可以实现对业务方法的再包装

除了jdk动态代理,还有一种叫做CGLib动态代理:

    程序执行时通过ASM(开源的Java字节码编辑库,操作字节码)jar包动态地为被代理类生成一个代理子类,通过该代理子类创建代理对象,由于存在继承关系,所以父类不能使用final修饰。

JDK动态代理与CGLib动态代理区别:
     1、JDK动态代理基于接口实现,所以实现JDK动态代理,必须先定义接口;CGLib动态代理基于类实现;
    2、JDK动态代理机制是委托机制,委托hanlder调用原始实现类方法;CGLib则使用继承机制,被代理类和代理类是继承关系,所以代理类是可以赋值给被代理类的,如果被代理类有接口,那么代理类也可以赋值给接口。

                                            

 

<think>好的,我现在要详细理解一下JDK动态代理。首先,用户可能已经知道代理模式的基本概念,但动态代理和静态代理有什么区别呢?动态代理是在运行时生成代理类,而静态代理需要手动编写代理类。那JDK动态代理具体是怎么实现的呢? 我记得JDK动态代理主要依赖于java.lang.reflect.Proxy类和InvocationHandler接口。Proxy类用来创建代理对象,而InvocationHandler负责处理代理对象的方法调用。用户可能需要知道具体的实现步骤,比如如何定义接口、实现InvocationHandler,以及使用Proxy.newProxyInstance方法生成代理对象。 不过,可能有些细节我记不太准,比如Proxy.newProxyInstance的参数顺序是否正确。应该是类加载器、接口数组和InvocationHandler实例。需要确认是否正确。还有,JDK动态代理只能代理接口,不能代理类,这点很重要,用户可能想知道为什么,或者有没有其他方式代理类,比如CGLIB。 另外,InvocationHandler的invoke方法参数包括代理对象、Method对象和参数数组。在实现时需要注意不要直接在invoke方法中调用代理对象的方法,否则会导致递归调用,出现栈溢出。这点需要提醒用户注意。 可能用户还关心动态代理的应用场景,比如Spring AOP中的使用,或者日志记录、事务管理、权限控制等横切关注点的处理。这时候可以举一个简单的例子,比如记录方法执行时间的日志代理。 另外,需要提到动态代理的优缺点。优点是无需手动编写代理类,减少代码冗余;缺点是不能代理类,只能代理接口,这可能会限制某些使用场景。这时候可以提到CGLIB库作为补充,它通过继承方式代理类,但在final类或方法上有局限性。 最后,是否应该比较一下JDK动态代理和CGLIB的区别?比如JDK基于接口,CGLIB基于继承,性能方面可能在不同版本中有差异,但现在可能差别不大。不过这可能超出用户当前的问题范围,可以简要提及。 总结回答的结构应该是:定义、实现步骤、关键类和接口、示例代码、应用场景、优缺点以及与其他技术的对比。需要确保示例代码正确,比如正确使用Proxy.newProxyInstance,正确实现InvocationHandler,并在invoke方法中添加增强逻辑。 可能还要检查一下术语是否正确,比如“横切关注点”是否准确,或者有没有拼写错误。另外,示例代码中的类名和方法名是否符合Java规范,比如接口和实现类的命名是否清晰,日志输出是否正确。 最后,确保语言口语化,避免过于技术化的表达,让用户容易理解。分步骤解释,逻辑清晰,让用户能够跟着步骤实现一个简单的动态代理例子。</think>关于JDK动态代理,我来分步骤为您详细解释: 1️⃣ **基本原理** JDK动态代理是Java原生支持的代理技术,通过在**运行时动态生成代理类**来实现功能增强。与需要手动编写代理类的静态代理不同,它就像"魔法师"一样在程序运行期间自动生成代理对象。 2️⃣ **核心组件** - `java.lang.reflect.Proxy`:生成代理类的工厂类 - `java.lang.reflect.InvocationHandler`:方法调用处理器(实现增强逻辑) 3️⃣ **实现步骤** 1. 定义业务接口 ```java public interface UserService { void saveUser(String username); } ``` 2. 实现目标类 ```java public class UserServiceImpl implements UserService { @Override public void saveUser(String username) { System.out.println("保存用户:" + username); } } ``` 3. 编写调用处理器 ```java public class LogHandler implements InvocationHandler { private final Object target; // 被代理对象 public LogHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("【日志】方法开始执行:" + method.getName()); long start = System.currentTimeMillis(); Object result = method.invoke(target, args); // 调用原始方法 long end = System.currentTimeMillis(); System.out.println("【日志】方法执行耗时:" + (end - start) + "ms"); return result; } } ``` 4. 生成代理对象 ```java public static void main(String[] args) { UserService target = new UserServiceImpl(); UserService proxy = (UserService) Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), new LogHandler(target) ); proxy.saveUser("张三"); // 通过代理调用方法 } ``` 4️⃣ **运行结果** ``` 【日志】方法开始执行:saveUser 保存用户:张三 【日志】方法执行耗时:3ms ``` 5️⃣ **特点分析** - ✅ 优势: - 无需手动编写代理类 - 可复用增强逻辑(如日志、事务等) - 符合开闭原则(对扩展开放,修改关闭) - ❌ 限制: - 只能代理接口(无法代理具体类) - 性能开销略高于直接调用(反射机制导致) 6️⃣ **应用场景** - 日志记录 - 事务管理 - 权限校验 - 性能监控 - 缓存处理 7️⃣ **与CGLIB对比** | | JDK动态代理 | CGLIB | |------------------|---------------------|---------------------| | 代理方式 | 基于接口 | 基于继承(子类化) | | 速度 | 较快(JDK8+优化) | 稍慢(需生成字节码)| | 依赖 | 无需额外库 | 需引入CGLIB库 | | 目标类限制 | 必须实现接口 | 不能是final类 | 📌 **最佳实践**:Spring框架默认优先使用JDK动态代理,当目标类没有接口时自动切换为CGLIB代理。 这种动态代理机制正是Spring AOP等框架实现面向切面编程的核心技术基础,通过它我们可以优雅地实现各种横切关注点的统一处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值