一个动态代理的实例

1、先编写一个接口

     

package com.test.dynamicproxy;

public interface MyInterface {
  public void fun();
}

2、用两个类来实现上面的接口

      

package com.test.dynamicproxy;
public class Wang implements MyInterface{

	@Override
	public void fun() {
		  System.out.println("wang的实现");
		
	}
}

 

 

package com.test.dynamicproxy;

public class Zhao implements MyInterface {

	@Override
	public void fun() {
			  System.out.println("zhao的实现");		
	}

}

 

3、编写服务器程序,这个类实现nvocationHandler接口

    

package com.test.dynamicproxy;

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

public class Handler implements InvocationHandler{
   private Object sub;
   

public void setSub(Object sub) {
	this.sub = sub;
}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("执行前");
	    method.invoke(sub,args);
		System.out.println("执行后");
		return null;
	}

}

4、编写代理类。

   

package com.test.dynamicproxy;
import java.lang.reflect.Proxy;
public class MyProxy {
	private Object obj;
	private Handler handler;
	
	
public void setObj(Object obj) {
			this.obj = obj;
		}

   public Object getproxy()
   {   
	   
       this.handler.setSub(obj);
	   return Proxy.newProxyInstance(Wang.class.getClassLoader(), Wang.class.getInterfaces(), handler);	 
   }


public void setHandler(Handler handler) {
	this.handler = handler;
}
}

   5、编写测试程序:

       

package com.test.dynamicproxy;

public class Client {
	public static void main(String[] args)
	{
	 Zhao zhao=new Zhao();
     Wang wang=new Wang();
     Handler handler=new Handler();
     MyProxy proxy=new MyProxy();
     
     proxy.setObj(wang);
     proxy.setHandler(handler);
     MyInterface face=(MyInterface)proxy.getproxy();
     face.fun();
     
     proxy.setObj(zhao);
     proxy.setHandler(handler);
     face=(MyInterface)proxy.getproxy();
     face.fun();
	}	
}

 

   至此一个简单的实例开发完毕了

你可能感兴趣的:(动态代理)