---
title: "Dynamic Proxy模式"
author: "woming66"
date: "2010-06-19T14:36:54Z"
tags: ["Java"]
categories: ["企业架构"]
slug: "dynamic-proxy"
draft: false
lastmod: "2010-06-19T14:36:54Z"
id: 694574
url: "https://woming66.iteye.com/blog/694574"
---

ProxyFactory类

```java

package com.zzq.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory implements InvocationHandler{
 
	private Object target;
	
	public ProxyFactory() {}
	
	public void setTarget(Object target) {
		this.target = target;
	}

	public Object createProxyBean() {
		
		return Proxy.newProxyInstance(
					target.getClass().getClassLoader(), 
					target.getClass().getInterfaces(), 
					this
				);
	}
	
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		
		Object result = null;
		try {
			this.before();
			
			result = method.invoke(target, args);
			
			this.afert();
		} catch (Exception e) {
			afterThrow(e);
		}
		return result;
	}
	
	public void before() {
		System.out.println("before");
	}
	
	public void afert() {
		System.out.println("afert");
	}
	
	public void afterThrow(Throwable t) {
		System.out.println("afterThrow");
		
		if(t instanceof InvocationTargetException) {
			t = t.getCause();
			System.out.println(t.getMessage());
		} else {
			System.out.println(t.getMessage());
		}
	}
}

```


```java

package com.zzq.proxy;

public interface SimpleBean {

	public void sayHello();
	
	public void throwException();
}

```


```java

package com.zzq.proxy;

public class SimpleBeanImpl implements SimpleBean {

	public void sayHello() {
		System.out.println("hello proxy pattern!");
	}
	
	public void throwException() {
		throw new RuntimeException("出错了");
	}
	
	public static void main(String[] args) {
		ProxyFactory factory = new ProxyFactory();
		
		factory.setTarget(new SimpleBeanImpl());
		
		SimpleBean proxy = (SimpleBean)factory.createProxyBean();
		
		proxy.sayHello();
		
		proxy.throwException();
	}
}

```