标签:proxy bubuko http hand bind tin this info src
1、创建接口
package com.oyy.mw.biz.i; public interface Cal { public int add(int num1,int num2); public int sub(int num1,int num2); public int mul(int num1,int num2); public int div(int num1,int num2); }
2、创建实现类
package com.oyy.mw.biz; import com.oyy.mw.biz.i.Cal; public class CalImpl implements Cal{ public int add(int num1, int num2) { int result = num1+num2; return result; } public int sub(int num1, int num2) { int result = num1-num2; return result; } public int mul(int num1, int num2) { int result = num1*num2; return result; } public int div(int num1, int num2) { int result = num1/num2; return result; } }
3、创建Java动态代理实现类
package com.oyy.mw.biz; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; public class MyInvocationHandler implements InvocationHandler { Object obj = null; /** * @param obj 接受传入的真实对象 * @return 返回代理对象 */ public Object bind(Object obj){ this.obj = obj; return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(method.getName()+"的参数是:"+Arrays.toString(args)); //调用方法,返回该方法返回的结果 Object result = method.invoke(obj, args); System.out.println(method.getName()+"的结果是:"+result); return result; } }
4、测试动态代理
package com.oyy.mw.test; import com.oyy.mw.biz.CalImpl; import com.oyy.mw.biz.MyInvocationHandler; import com.oyy.mw.biz.i.Cal; public class Test { public static void main(String[] args) { Cal cal1 = new CalImpl(); MyInvocationHandler handler = new MyInvocationHandler(); Cal cal = (Cal)handler.bind(cal1); cal.add(10, 3); cal.sub(10, 3); cal.mul(10, 3); cal.div(10, 3); } }
5、打印结果
标签:proxy bubuko http hand bind tin this info src
原文地址:https://www.cnblogs.com/ouyy/p/10265923.html