InvocationHandler_demo
参考:Java动态代理之InvocationHandler - 知乎 (zhihu.com)
(15条消息) java动态代理Proxy.newProxyInstance_一笑而过者也的博客-CSDN博客
(15条消息) Java - 动态代理机制讲解(Proxy.newProxyInstance)_放羊的牧码的博客-CSDN博客
IHello.java
package com.hmb; public interface IHello { void sayHello(); void sayGoodBye(); }
HelloImpl.java
1 package com.hmb; 2 3 public class HelloImpl implements IHello { 4 @Override 5 public void sayHello() { 6 System.out.println("hello impl"); 7 } 8 9 @Override 10 public void sayGoodBye() { 11 System.out.println("goodbye impl"); 12 } 13 }
HelloHandler.java
1 package com.hmb; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 6 public class HelloHandler implements InvocationHandler { 7 8 private final IHello iHello; 9 10 public HelloHandler(IHello iHello) { 11 this.iHello = iHello; 12 } 13 14 @Override 15 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 16 String methodName = method.getName(); 17 18 switch (methodName) { 19 case "sayHello": 20 System.out.println("log before sayHello"); 21 method.invoke(iHello, args); 22 break; 23 case "sayGoodBye": 24 System.out.println("log before sayGoodBye"); 25 method.invoke(iHello, args); 26 break; 27 default: 28 System.out.println("log before other method"); 29 method.invoke(iHello, args); 30 } 31 32 return null; 33 } 34 }
Main.java
1 package com.hmb; 2 3 import java.lang.reflect.Proxy; 4 5 public class Main { 6 public static void main(String[] args) { 7 IHello hello = new HelloImpl(); 8 IHello iHello = (IHello) Proxy.newProxyInstance(hello.getClass().getClassLoader(), 9 hello.getClass().getInterfaces(), 10 new HelloHandler(hello)); 11 iHello.sayHello(); 12 iHello.sayGoodBye(); 13 } 14 }
执行结果
其他
- 报以下错误说明handler类中的invoke方法实现错误,第一个参数漏传入要代理的对象iHello