---
title: "动态代理"
author: "一杯白开水w"
date: "2015-06-28T21:15:49Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2015-06-30T08:07:17Z"
id: 2222694
url: "https://wlt2008-com.iteye.com/blog/2222694"
---

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

public class InvocationHandlerImpl implements InvocationHandler {

	private Object targetObject;//要代理的目标对象
	
	// 通过构造方法 传入要代理的目标对象
	public InvocationHandlerImpl(Object targetObject) {
		this.targetObject = targetObject;
	}
	// 创建代理对象
	public Object createProxyInstance(){
		 Object proxyInstance = Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), 
							   targetObject.getClass().getInterfaces(),
							   this);
		return proxyInstance;
		
	}


	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		long start = System.currentTimeMillis();
		System.out.println(start);
		
		//调用目标对象的方法
		Object result = method.invoke(targetObject, args);
		
		long end = System.currentTimeMillis();
		System.out.println(end);
		System.out.println("执行时间："+(end-start)+"毫秒");
		return result;
	}

}
```

 

测试：

```
package com.bjpowernode.dao;

import junit.framework.TestCase;

public class ContactDaoTest extends TestCase {

	public void testSave() {
		ContactDao dao1 = new ContactDaoImpl();
		//dao1.save();
	
		
		ContactDao dao =(ContactDao) new InvocationHandlerImpl(dao1).createProxyInstance();
	//	dao.save();
		System.out.println(dao.delete());
		//dao.update();
	}

}
```