通过使用java.lang.reflect.Proxy实现动态代理

/**
 *  2014-4-19
 *  动态代理比代理的思想更进一步,可以动态地创建代理,并且可以动态地调用被代理的方法。
 *
 */
package typeinfo;

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


/**
 * 定义出代理对象的接口
 * @author LYL
 *
 */
interface Interface{
	void doSomething();
	void somethingElse(String arg);
}

/**
 * 被代理的对象,是真正干活的
 * @author LYL
 *
 */
class RealObject implements Interface{

	@Override
	public void doSomething() {
		System.out.println("RealObject doSomething");
	}

	@Override
	public void somethingElse(String arg) {
		System.out.println("RealObject somethingElse"+arg);
	}
}
/**
 * 定义代理类调用被代理类的方法时的逻辑
 * @author LYL
 *
 */
class ProxyHandler implements InvocationHandler
{
	//被代理对象
	private Interface proxied;
	public ProxyHandler(Interface proxied){
		this.proxied=proxied;
	}
	/**
	 * 调用处理器,当动态代理进行方法调用时,将使用该处理器。
	 * 可以在该方法中对指定的方法进行定制,特殊处理。
	 */
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("Proxy:"+proxy.getClass()+", method:"+method+" , args:"+args);
		//显示参数
		if(args!=null){
			for(Object arg:args){
				System.out.println("   "+arg);
			}
		}
		//调用被代理类的方法
		return method.invoke(this.proxied, args);
	}
}

/**
 * 通过使用java.lang.reflect.Proxy创建动态代理的实例
 * @author LYL
 *
 */
public class SimpleDynamicProxy{
	public static void consumer(Interface iface){
		iface.doSomething();
		iface.somethingElse(" invoke ");
	}

	public static void main(String args[]) throws Exception{
		RealObject real=new RealObject();
		//对象的一般调用
		consumer(real);
				
		//创建一个动态代理
		Interface iface=(Interface)Proxy.newProxyInstance(
				//类加载器,
				Interface.class.getClassLoader(), 
				//代理类实现的接口或基类数组
				new Class[]{Interface.class}, 
				//代理处理器
				new ProxyHandler(new RealObject()));
		
		System.out.println("通过动态代理生成的代理类实例");
		//通过生成的动态代理来执行功能
		consumer(iface);
	}
}
原文地址:https://www.cnblogs.com/bjwylpx/p/3675444.html