动态代理的过程

package com.jd.calculator;

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

首先看main方法:第一行代码
“System.getProperties().put(“sun.misc.ProxyGenerator.saveGeneratedFiles”, “true”);”作用是把产生的动态Class类的class文件编译出来,方便我们反编译它来观察产生的动态类。
第二行代码 给成员变量赋值
第三行代码 test.get()调用get方法,该方法产生动态Class类
newProxyInstance方法源代码如下:

 public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值