實現一個JDK代理demo
阿新 • • 發佈:2018-11-15
JDK代理,非常簡單地實現了動態代理(首先是實現對應的InvocationHandler;然後,以介面來為被呼叫目標構建代理物件,代理物件簡介執行呼叫目標,並提供額外邏輯插入)
缺點:它是隻能以介面為中心的。優點:依賴JDK,更穩定可靠,跟著JDK升級,程式碼簡單。
1 package jesse.test; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 import java.lang.reflect.Proxy; 6 7 interfaceHello{ 8 void sayHello(); 9 } 10 11 class HelloImpl implements Hello{ 12 13 @Override 14 public void sayHello() { 15 System.out.println("my hello"); 16 } 17 18 } 19 20 class MyInvocationHandler implements InvocationHandler{ 21 private Object target; 22 publicMyInvocationHandler(Object target) { 23 super(); 24 this.target = target; 25 } 26 @Override 27 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 28 System.out.println("proxy invoke sayhello"); 29 Object result = method.invoke(target, args);30 return result; 31 } 32 } 33 34 public class MyJDKProxy { 35 public static void main(String[] args) { 36 HelloImpl hello = new HelloImpl(); 37 MyInvocationHandler handler = new MyInvocationHandler(hello); 38 //構造程式碼例項 39 Hello proxyHello = (Hello)Proxy.newProxyInstance(HelloImpl.class.getClassLoader(), HelloImpl.class.getInterfaces(),handler); 40 //呼叫代理方法 41 proxyHello.sayHello(); 42 } 43 44 }