JDK动态代理执行过程分析

本文详细分析了JDK动态代理的执行过程,从为什么使用动态代理开始,逐步解析JDK动态代理的生成和执行步骤,并对比了CGLib动态代理与JDK的区别。动态代理在Java中提供了一种灵活的代码优化方式,通过接口实现,允许在运行时生成代理类。
摘要由CSDN通过智能技术生成

                                               JDK动态代理执行过程分析


文章目录

       一、为什么使用动态代理

       二、JDK动态代理执行过程分析

       三、CGLib动态代理与JDK的区别


一、为什么使用动态代理

类中代码可以通过代理模式进行优化,Java中代理模式分为静态代理和动态代理,动态代理又分为JDK动态代理和CGLib动态代理。


二、JDK动态代理执行过程分析

CalculatorService中的代码

package com.jd.calculator;

public class CalculatorService implements ICalculatorService {

	@Override
	public int add(int a, int b) {
		int result = a+b;
		return result;
	}

	@Override
	public int sub(int a, int b) {
		int result = a-b;
		return result;
	}

	@Override
	public int mul(int a, int b) {
		int result = a*b;
		return result;
	}

	@Override
	public int div(int a, int b) {
		int result = a/b;
		return result;
	}
}

ICalculatorService中的代码

package com.jd.calculator;

public interface ICalculatorService {

	int add(int a,int b);
	
	int sub(int a,int b);
	
	int mul(int a,int b);
	
	int div(int a,int b);
}

Test中的代码

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 = 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值