Dynamic Proxy模式

ProxyFactory类

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());
		}
	}
}

 

package com.zzq.proxy;

public interface SimpleBean {

	public void sayHello();
	
	public void throwException();
}

 

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();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值