`

动态代理(Dynamic Proxy)

 
阅读更多
代码例子:
package com.test;
/**
 * 一个真实的接口
 * @author yale
 *
 */
public interface ISubject
{
	public void request();
}

package com.test;
/**
 * 一个真实的对象
 * @author yale
 *
 */
public class RealSubject implements ISubject
{

	public void request()
	{
		System.out.println("real subject request");
		
	}

}


package com.test;

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

/**
 * 一个动态代理对象,实现InvocationHandler
 * @author yale
 *
 */
public class DynamicSubject implements InvocationHandler
{  
	private Object obj;//被代理的对象
	
	public DynamicSubject(Object o)
	{
		this.obj = o;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable
	{
		System.out.println("before request");
        method.invoke(obj,args);
        System.out.println("after request");
		return null;
	}

}


package com.test;

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

/**
 * 调用测试
 * 
 * @author yale
 * 
 */
public class Client
{
	public static void main(String[] args)
	{
		RealSubject realSubject = new RealSubject();

		InvocationHandler handler = new DynamicSubject(realSubject);

		Class<?> classType = handler.getClass();

		ISubject subject = (ISubject) Proxy.newProxyInstance(classType
				.getClassLoader(), realSubject.getClass().getInterfaces(),
				handler);
		
		subject.request();
	}
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics