---
title: "JDK动态代理"
author: "winseclone"
date: "2013-02-23T18:06:41Z"
tags: []
categories: ["编程语言"]
slug: "jdk"
draft: false
lastmod: "2013-03-02T19:56:49Z"
id: 1813825
url: "https://winseclone.iteye.com/blog/1813825"
---

动态之处在于代理类在运行时才产生。代码开始执行时没有proxy类，根据需要从传入的接口来创建proxy类。

 

1、 创建接口及其实现类

```
public interface Animal {

	String getName();
	
}
```

 

```
public class Person implements Animal {

	@Override
	public String getName() {
		return "John.";
	}

}
```

 

2、 实现自定义的InvocationHandler

```
public class Invoker implements InvocationHandler {

	private Object obj;

	public Invoker(Object real) {
		this.obj = real;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.println("start...");

		return method.invoke(obj, args);
	}
```

 

3、 测试

```
	public static void main(String[] args) {
		System.setProperty(
				"sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

		Person real = new Person();
		Invoker invoker = new Invoker(real);

		Animal proxy = (Animal) Proxy.newProxyInstance( //
				Animal.class.getClassLoader(), 
				new Class[] { Animal.class }, 
				invoker);

		System.out.println(proxy.getName());
	}
```

 

设置的sun.misc.ProxyGenerator.saveGeneratedFiles参数是为了把动态生成的字节码文件保存下来。以便查看。

 

## · 代理模式 vs 装饰者模式

从代码上来说很像。有相同的超类。

装饰模式是起点缀作用，给对象赋予新的职责，装饰对象。

       动态地将责任附加到对象上，若要扩展功能，装饰者提供了比继承更有弹性的替代方案。

在原来的基础上添加行为（职责），也就是说原本的对象一定得存在。

 

代理模式则是控制和管理对象的访问，代表对象，替身。

       为另一个对象提供一个替身或占位符控制对这个对象的反问。

原本对象可能不存在。远程代理，虚拟代理（如动态加载图片）

 

## 参考文章：

1、 动态代理的例子实现及其JDK代码分析 [http://blog.csdn.net/z69183787/article/details/8263995](http://blog.csdn.net/z69183787/article/details/8263995)

2、 AOP的一篇文章，同时也介绍了动态AOP代理 [http://www.iteye.com/topic/1116696](http://www.iteye.com/topic/1116696)

3、 sun.misc.ProxyGenerator源码 [http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/misc/ProxyGenerator.java#ProxyGenerator.0saveGeneratedFiles](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/misc/ProxyGenerator.java#ProxyGenerator.0saveGeneratedFiles)