java中InvocationHandler 用于实现代理。

InvocationHandler 用于实现代理。

如果不用InvocationHandler接口实现代理的话,我们写代码是这样的:
定义一个接口:

Java code
 
    
interface Greet { void sayHello(String name); void goodBye(); }



实现这个接口:

Java code
 
    
class GreetImpl implements Greet { public void sayHello(String name) { System.out.println( " Hello " + name); } public void goodBye() { System.out.println( " Good bye. " ); } }



实现一个代理类

Java code
 
    
public class SimpleProxy implements Greet { private Greet greet = null ; SimpleProxy(Greet greet) { this .greet = greet; } public void sayHello(String name) { System.out.println( " --before method sayHello " ); greet.sayHello(name); System.out.println( " --after method sayHello " ); } public void goodBye() { System.out.println( " --before method goodBye " ); greet.goodBye(); System.out.println( " --after method goodBye " ); } /** * @param args */ public static void main(String[] args) { Greet greet = new SimpleProxy( new GreetImpl()); // 生成代理 greet.sayHello( " walter " ); greet.goodBye(); } }




代理其实没什么的,再看看如果实现了InvocationHandler接口,
我们怎样实现代理。
还是要实现原来的Greet接口。
接口的实现还是GreetImpl。

Java code
 
    
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class DebugProxy implements java.lang.reflect.InvocationHandler { private Object obj; public static Object newInstance(Object obj) { return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new DebugProxy(obj)); } private DebugProxy(Object obj) { // Greet接口的實現:GreetImpl this .obj = obj; } // Method m:調用的方法 // Object[] args:方法要傳入的參數 public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { Object result; try { // 自定義的處理 System.out.println( " --before method " + m.getName()); // 調用GreetImpl中方法 result = m.invoke(obj, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw new RuntimeException( " unexpected invocation exception: " + e.getMessage()); } finally { System.out.println( " --after method " + m.getName()); } return result; } /** * @param args */ public static void main(String[] args) { Greet tmp = new GreetImpl(); Greet greet = (Greet) DebugProxy.newInstance(tmp); // 生成的greet和tmp有相同的hashCode greet.sayHello( " walter " ); greet.goodBye(); } }

你可能感兴趣的:(JAVA)