zoukankan      html  css  js  c++  java
  • java 动态代理理解

    动态代理,顾名思义就是动态创建一个代理对象,无需手动为被代理类创建一个代理类,java的动态代理通过Proxy类和Invocation接口实现,代码如下:

    //被代理接口

    public interface HelloWorld {
      public void test();
    }

    //Handler

    public class TestHandler implements InvocationHandler {

      public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
        System.out.println("result");
        return null;
      }
    }

    //测试类

    public class TestMyBatis {
      public static void main(String[] args) {
        HelloWorld helloWorld = (HelloWorld)Proxy.newProxyInstance(HelloWorld.class.getClassLoader(), new Class[]{HelloWorld.class}, new TestHandler());
        helloWorld.test();
      }
    }

    这个例子,仅仅根据接口生成一个代理类,并且交给handler处理(mybatis中就是这么干的)这样可以把业务逻辑写到invoke方法中,实现低耦合。

    invoke的三个参数说明:Object proxy:代理类的实例,上述例子中的helloWorld对象,Method method:执行的方法,上述例子中的test方法,Object[] args:method方法的参数,上述例子中参数为空,所以此处为空。

  • 相关阅读:
    12_2 数据分析工具包。
    11_29
    11_28 mongoDB与scrapy框架
    11_28,selenium定位元素,cookies获取
    11_26爬虫find与findall
    day_93_11_25爬虫一requests,项目框架
    11_14flask的启动和orm,反向生成model
    11_13Local与偏函数
    11_12 路由与正则
    day83_11_1 阿里配python使用。
  • 原文地址:https://www.cnblogs.com/lqfu/p/4730862.html
Copyright © 2011-2022 走看看