---
title: "java动态代理简单实现"
author: "weistar"
date: "2012-06-30T09:45:45Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: true
lastmod: "2012-06-30T09:45:26Z"
id: 1571403
url: "https://weistar.iteye.com/blog/1571403"
---

一.接口

```
public interface Foo {

	public void doThing();
}
```

二.接口实现

```
public class FooImpl implements Foo {

	@Override
	public void doThing() {
		System.out.println("Java Dynamic Proxy success");
	}

}
```

 三.接口代理

```
public class FooProxy implements InvocationHandler {

	private Object obj;

	public FooProxy(Object obj) {
		this.obj = obj;
	}

	public static Object newInstance(Object obj) {
		return Proxy.newProxyInstance(obj.getClass()
				.getClassLoader(), obj.getClass().getInterfaces(),
				new FooProxy(obj));
	}

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

		method.invoke(obj, args);

		System.out.println("after calling " + method);

		return null;
	}

}
```

 四.使用代理对象

```
public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Foo foo = (Foo)FooProxy.newInstance(new FooImpl());
		foo.doThing();
	}

}
```