java dynamic proxy,动态代理

package dynamicproxy;

public interface SimpleInterface {

	void doSth();

	void doSthElse(String s);

}

  

package dynamicproxy;



public class RealObject implements SimpleInterface {



	@Override

	public void doSth() {

		System.out.println("Real Object do sth");

		

	}



	@Override

	public void doSthElse(String s) {

		System.out.println("Real Object do sth Else:"+s);		

	}



}

package dynamicproxy;



import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;



public class DynamicProxyHandler implements InvocationHandler {



	private Object object;

	public DynamicProxyHandler(Object o){

		this.object=o;

	}

	@Override

	public Object invoke(Object proxy, Method method, Object[] args)

			throws Throwable {

		System.out.println("DynamicProxyHandler process.传来的代理:"+ proxy.getClass());

		return method.invoke(object, args);

	}



}

package dynamicproxy;



import java.lang.reflect.Proxy;



public class Test {



	static void consumer(SimpleInterface obj){

		obj.doSth();

		obj.doSthElse("你去处理一下");

	}

	/**

	 * @param args

	 */

	public static void main(String[] args) {



		RealObject obj=new RealObject();

		consumer(obj);

		

		SimpleInterface proxObj = (SimpleInterface) Proxy.newProxyInstance(

				SimpleInterface.class.getClassLoader(),

				new Class[] { SimpleInterface.class },

				new DynamicProxyHandler(obj));

		consumer(proxObj);

	}



}

你可能感兴趣的:(dynamic proxy)