1 package com.yhqtv.java; 2 3 /* 4 * @author XMKJ yhqtv.com Email:yhqtv@qq.com 5 * @create 2020-05-11-12:12 6 * 7 */ 8 9 import java.lang.reflect.InvocationHandler; 10 import java.lang.reflect.Method; 11 import java.lang.reflect.Proxy; 12 13 interface Human { 14 15 String getBelief(); 16 17 void eat(String food); 18 } 19 20 //被代理类 21 class SuperMan implements Human { 22 23 @Override 24 public String getBelief() { 25 return "I believe I can fly"; 26 } 27 28 @Override 29 public void eat(String food) { 30 System.out.println("我喜欢吃" + food); 31 } 32 } 33 34 class ProxyFactory { 35 //调用此方法,返回一个代理类的对象 36 public static Object getProxyInstance(Object obj) {//obj:被代理类的对象 37 38 MyInvocationHandler handler = new MyInvocationHandler(); 39 handler.bind(obj); 40 41 return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler); 42 } 43 } 44 45 class MyInvocationHandler implements InvocationHandler { 46 47 private Object obj;//需用使用被代理类的对象进行赋值 48 49 public void bind(Object obj) { 50 this.obj = obj; 51 } 52 53 //当我们通过代理类的对象,调用方法a时,就会自动的调用如下的方法:invoke() 54 //将被代理类要执行的方法a的功能就声明在invoke()中 55 @Override 56 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 57 58 //method:即为代理类对象调用的方法,此方法也就作为了被代理类对象要调用的方法 59 //obj:被代理类的对象 60 Object returnValue = method.invoke(obj, args); 61 //上述方法的返回值就作为当前类中的invoke()的返回值 62 return returnValue; 63 64 } 65 } 66 67 public class ProxyTest { 68 public static void main(String[] args) { 69 70 SuperMan superMan = new SuperMan(); 71 //proxyInstance:代理类的对象 72 Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan); 73 74 //当通过代理类对象调用方法时,会自动的调用被代理类中同名的方法 75 String belief = proxyInstance.getBelief(); 76 System.out.println(belief); 77 proxyInstance.eat("面条"); 78 79 80 } 81 82 }
原文:https://www.cnblogs.com/yhqtv-com/p/12868533.html