---
title: "JDK动态代理模式"
author: "哈达f"
date: "2012-12-22T21:51:49Z"
tags: []
categories: ["编程语言"]
slug: "jdk"
draft: false
lastmod: "2012-12-22T21:51:49Z"
id: 1752465
url: "https://myitdream.iteye.com/blog/1752465"
---

```
package cn.dhcool.dynamic.proxy;

public interface CommonInterface {
	
	public void speak();

}
```

 

```
package cn.dhcool.dynamic.proxy;

public class RealObject implements CommonInterface{

	@Override
	public void speak() {
		System.out.println("你好");		
	}

}
```

 

 

```
package cn.dhcool.dynamic.proxy;

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

public class MyInvocationHandler implements InvocationHandler{
	
	private CommonInterface realObject;
	
	public MyInvocationHandler(){}
	
	public MyInvocationHandler(CommonInterface realObject){
		this.realObject = realObject;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		Method[] methods = realObject.getClass().getMethods();
		for (int i = 0; i < methods.length; i++) {
			if(methods[i].getName().equals(method.getName())){
				this.checkInfo();
				methods[i].invoke(this.realObject, args);
				break;
			}
		}
		return null;
	}
	
	//代理模式调用的方法
	public void checkInfo(){
		System.out.println("运行方法前先调用的检查方法!");
	}
}
```

 

 

```
package cn.dhcool.dynamic.proxy;

import java.lang.reflect.Proxy;

public class Client {
	
	public static void main(String[] args) {
		
		CommonInterface realObject = new RealObject();
		/*
		 * 代理模式需要的条件，一个公共的接口，一个真实实现的类，一个代理类同样实现了公共接口
		 * 现在我们有了接口和实现类，我们还需要一个代理类，我们的代理类可以通过JDK的Proxy类动态为我们创建
		 * 通过反射方式去调用
		 * InvocationHandler 一个接口处理类，接口回调方法，类似与SpringTemple 模版操作JDBC的接口回调
		 * 还有DBUtil的ResultSetHandler接口，都是一种接口回调的思想。
		 * */
		//采用JDK动态代理类动态创建代理类
		CommonInterface proxyObject = (CommonInterface)Proxy.newProxyInstance(realObject.getClass().getClassLoader(), 
							realObject.getClass().getInterfaces(), new MyInvocationHandler(realObject));
		proxyObject.speak();
	}

}
```