1. 程式人生 > >java的動態代理

java的動態代理

validate main mar print south trac result ins ack

動態代理類

package itbuluoge.proxy;

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

public class DynamicProxy implements InvocationHandler{

	private Object obj;
	public Object bind(Object obj)
	{
		this.obj=obj;
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
	}
	public Object invoke(Object arg0, Method method, Object[] args)
			throws Throwable {
		Object result=null;
		try
		{
			validateUser();
			result=method.invoke(obj,args);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	public void validateUser()
	{
		System.out.println("驗證用戶...");
	}

}


測試類

package itbuluoge.proxy;

public class TestDynamic {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DynamicProxy dp=new DynamicProxy();
		ICompent com=(ICompent)dp.bind(new Compent());
		com.bussiness1();
		com.bussiness2();
		com.bussiness3();
	}

}


輸出結果

技術分享



靜態代理見文章:http://blog.csdn.net/itbuluoge/article/details/40046377

java的動態代理