Java中的动态代理技术
来源:互联网 发布:java中多态的表现形式 编辑:程序博客网 时间:2024/05/23 18:33
动态代理在日常的开发中还是比较重要的,下面来总结一下。
首先,什么是动态代理技术呢?当项目中有几个类,每一个类都需要做一些类似的操作,比方说打印日志,现在需求可能有更改,那么你必须要改变每一个类中的相关的方法,如果使用动态代理的话就会轻松很多,因为你只需要在InvocationHandler的invoke方法中做相关的操作即可。
ex:
规定一个接口:
public interface AtitheticCalculator { int add(int i,int j); int sub(int i,int j); int mul(int i,int j); int div(int i,int j);}
下面是它的实现类:
public class AtitheticCalculatorImp implements AtitheticCalculator { public int add(int i, int j) { int result=i+j; return result; } public int sub(int i, int j) { int result=i-j; return result; } public int mul(int i, int j) { int result=i*j; return result; } public int div(int i, int j) { int result=i/j; return result; }}然后是相关的代理类:
public class AtithmeticCalculatorLoggingProxy { private AtitheticCalculator target;//要代理的对象 public AtithmeticCalculatorLoggingProxy(AtitheticCalculator target) { this.target = target; } public AtitheticCalculator getLoggingProxy(){ AtitheticCalculator proxy=null; //代理对象由哪一个类加载器进行加载 ClassLoader loader=target.getClass().getClassLoader(); //代理对象的类型,即其中有哪些方法 Class[] interfaces=new Class[]{AtitheticCalculator.class}; //返回代理对象后的处理 InvocationHandler h=new InvocationHandler() { /** * proxy:正在返回的那个代理对象,一般情况下在invoke方法中不是用该对象(有可能会造成死循环) * method:正在被调用的那个对象 * args:调用方法的时候传入的那个参数 * */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { /*System.out.println("invoke..."); return 0;*/ String methodName=method.getName(); //日志 System.out.println("The method "+methodName+" begin with"+ Arrays.asList(args)); //执行方法 Object result=method.invoke(target,args); //日志 System.out.println("The method"+methodName+"ends with"+result); return result; } }; proxy= (AtitheticCalculator) Proxy.newProxyInstance(loader,interfaces,h); return proxy; }}
在代理类中我们通过反射获取到需要代理的对象,然后可以在
InvocationHandler的invoke()函数中可以进行相关的操作,这里将调用的方法名称以及结果进行了输出
最后来看一下主程序:
public class Main { public static void main(String[] args) { AtitheticCalculator target=new AtitheticCalculatorImp(); AtitheticCalculator proxy=new AtithmeticCalculatorLoggingProxy(target).getLoggingProxy(); /*int result=target.add(1,2);*/ int result=proxy.add(1,2); System.out.println("--->"+result); /*result=target.div(4,2);*/ int result1=proxy.div(4,2); System.out.println("--->"+result1); }}输出结果:
0 0
- Java中的动态代理技术
- 【黑马程序员】java中的--------------代理类与动态代理技术
- java动态代理技术
- JAVA中的代理技术
- java中的动态代理
- java中的动态代理》》》》》
- JAVA 中的 动态代理
- java中的动态代理
- java中的动态代理
- Java中的动态代理
- Java中的动态代理
- JAVA中的动态代理
- java中的动态代理
- java中的动态代理
- java 中的动态代理
- Java中的动态代理
- java中的动态代理
- Java中的动态代理
- Python:eval的妙用和滥用
- opencv使用cmake链接库函数出现usr/bin/ld: cannot find -lopencv_终极解决方案
- fetch
- 一次同余式的求解(扩展欧几里得)
- 优秀的第三方常用控件
- Java中的动态代理技术
- maven assembly plugin使用
- Struts2拦截器的使用 (详解)
- 可点进来看看的一些Python基础
- JDk1.6中文版 math类
- springMVC+MyBatis+meaven整合的pom.xml配置文件
- Apache+Tomcat部署负载均衡(或集群)
- 最终一致性算法Gossip简介
- php 格式化字节大小