Java代理:Proxy InvocationHandler


  
  
           
  
  
  1. public interface IHelloWorld { 
  2.      
  3.     void sayHello(); 
  4.      

 

  
  
           
  
  
  1. public class HelloWorldImpl implements IHelloWorld { 
  2.  
  3.     public void sayHello() { 
  4.         System.out.println("Hello World!!"); 
  5.     } 
  6.  

 

  
  
           
  
  
  1. public class HelloWorldHandler implements InvocationHandler { 
  2.  
  3.     IHelloWorld object; 
  4.      
  5.     public HelloWorldHandler(IHelloWorld object) { 
  6.         this.object = object; 
  7.     } 
  8.  
  9.     public Object invoke(Object proxy, Method method, Object[] args) 
  10.             throws Throwable { 
  11.         System.out.println("before"); 
  12.         Object o = method.invoke(object, args); 
  13.         System.out.println("after"); 
  14.         return o; 
  15.     } 
  16.  

 

  
  
           
  
  
  1. public class proxyDemo { 
  2.  
  3.     public static void main(String[] args) { 
  4.         InvocationHandler handler = new HelloWorldHandler(new HelloWorldImpl()); 
  5.         IHelloWorld proxy = (IHelloWorld)Proxy.newProxyInstance( 
  6.                 HelloWorldImpl.class.getClassLoader(),  
  7.                 HelloWorldImpl.class.getInterfaces(),  
  8.                 handler); 
  9.         proxy.sayHello(); 
  10.     } 
  11.  

 

before
Hello World!!
afteride