接口及实现类
1 public interface DynamicProxy { 2 3 String sayHello(); 4 5 }
1 public class DynamicProxyImpl implements DynamicProxy { 2 3 @Override 4 public String sayHello() { 5 return "Hello World!"; 6 } 7 8 }
主要类
1 public class JdkProxyExample implements InvocationHandler { 2 3 private Object target; 4 5 public Object bind(Object target) { 6 this.target = target; 7 return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); 8 } 9 10 @Override 11 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 12 System.out.println("前处理"); 13 Object object = method.invoke(this.target, args); 14 System.out.print(object); 15 System.out.println(" 处理中"); 16 System.out.println("后处理"); 17 return object; 18 } 19 20 }
调用方
1 public class DynamicProxyCaller { 2 3 public void foo() { 4 JdkProxyExample jdkProxyExample = new JdkProxyExample(); 5 DynamicProxy dynamicProxy = (DynamicProxy) jdkProxyExample.bind(new DynamicProxyImpl()); 6 System.out.println(dynamicProxy.sayHello()); 7 } 8 9 }
原文:https://www.cnblogs.com/bxcube/p/12229964.html