//测试程序
import java.lang.reflect.Proxy;
public class DynamicProxyTest
{
	public static void main(String[] args)  throws Exception
	{
		// TODO Auto-generated method stub
		Show show = new ShowImp();
		Show exampleProxy = (Show)Proxy.newProxyInstance
		(
				show.getClass().getClassLoader(),
				show.getClass().getInterfaces(),
				new Handler()
		);
	
		exampleProxy.showOne();
		exampleProxy.showTwo();
	}
}

//接口Show
public interface Show
{
	void showOne();
	void showTwo();
}

//接口Show的实现类ShowImp
public class ShowImp implements Show
{

	public void showOne()
	{
		// TODO Auto-generated method stub
		System.out.println("interface show : showOne()");

	}

	public void showTwo()
	{
		// TODO Auto-generated method stub
		System.out.println("interface show : showTwo()");

	}
	
	/*public void showThree()
	{
		System.out.println("Example : showThree()");
	}*/

}

//实现InvocationHandler接口,作为Proxy.newProxyInstance()的第三个参数
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class Handler implements InvocationHandler
{
	public Object invoke(Object proxy,Method method,Object[]args) 
	{
		System.out.println("IvocationHandler handle");
		return null;
	}

}

测试结果:

由于Proxy.newProxyInstance()的参数只提供了接口,所以InvocationHandler只能接手接口中的方法,

通过 Proxy.newProxyInstance() 也是只能返回接口的实例,

所以说思路很明确,这个代理就是代理作为参数的接口的,通过代理来访问接口中的方法,将被IvocationHandler的invoke()方法处理


题外话:Show show = new ShowImp(); show.getClass().getName() 返回的show的实际类型的名字

而不是声明类型的名字