了解Java代理(二):JDK动态代理

前言

        上个章节,了解到了静态代理的不够灵活的缺点,为了适应更多的应用场景,我们可以引入动态代理,本章主要先围绕JDK动态代理做一些内容。

1、阐述JDK动态代理

        想要实现JDK动态代理我们需要了解以下两点:

         1、在JDK动态代理上所作的所有调用都会被重定向到一个单一的调用处理器上,调用处理器需要实现InvocationHandler接口,该接口只有一个invoke()方法需要实现。

         2、通过静态方法Proxy.newInstance()可以创建动态代理,该方法的入参有三个:一个类加载器,一个需要代理实现的接口列表,一个调用处理器。

        话不多说,我们通过代码实现能更直观理解。

2、代码实现

        代理实例沿用上章中的老师课代表例子。

        1、首先,创建一个Person接口,包含一个doSomething和一个doOtherThing方法。老师和课代表都是人,会做的事不止一件,所以后续的老师类(实际对象)类会实现这个接口:

public interface Person {

    void doSomething();

    void doOtherThing();

}

        2、创建老师类(实际对象),实际做的事是批改作业或者查看作业:

/**
 * 老师
 */
public class Teacher implements Person {

    @Override
    public void doSomething() {
        System.out.println("老师:批改作业");
    }

    @Override
    public void doOtherThing() {
        System.out.println("老师:查看作业");
    }
}

        3、由于是动态代理,该步骤不同于静态代理(可看上章节),不会直接创建课代表(代理类),而是创建一个阐述中提到的调用处理器,处理器中的invoke方法接手了原本课代表(代理类)需要做的事:

public class RepresentativeHandler implements InvocationHandler {

    //需要代理的实际对象
    private Person person;

    public RepresentativeHandler(Person person) {
        this.person = person;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("课代表:收作业");
        Object result = method.invoke(person, args);
        System.out.println("课代表:发作业");
        return result;
    }
}

        4、这次就不演示无代理的代码执行情况了,为了方便后续代理情况的演示,学生类也不创建了,直接演示代理:

public class JdkDynamicTest {
    public static void main(String[] args) {
        //老师
        Person teacher = new Teacher();

        //课代表
        Person representative = (Person)Proxy.newProxyInstance(
                teacher.getClass().getClassLoader(),
                teacher.getClass().getInterfaces(),
                new RepresentativeHandler(teacher)
        );

        //学生交作业
        System.out.println("学生:交作业");
        representative.doSomething();
    }
}

        运行结果:

学生:交作业
课代表:收作业
老师:批改作业
课代表:发作业

        可以看到,课代表的生成是通过阐述中的第二点调用Proxy.newInstance方法创建的,需要注意的是:

1、第一个参数需要一个类加载器,通常从一个已经被加载的对象中就可以获取到;

2、第二个参数需要的是代理实现的接口列表,即我们生成的课代表类需要实现的接口;

3、第三个参数就是调用处理器,构建处理器时传入了实际需要被代理的对象(老师)

4、该方法返回值是一个Object类,示例中已经确定需要代理的是实现了Person接口的老师类,返回的代理对象也是一样的,直接强转成Person即可。

5、在写代码我们可能看到有两个Proxy可以引用,导入java.lang.reflect包下的Proxy。

        5、得到的结果和上章节静态代理是一样的,但动态代理更灵活,记得这次Person接口中多了doOtherThing方法吗,老师实现该方法后实际是查看作业,该方法也被代理了:

public class JdkDynamicTest {
    public static void main(String[] args) {
        //老师
        Person teacher = new Teacher();

        //课代表
        Person representative = (Person)Proxy.newProxyInstance(
                teacher.getClass().getClassLoader(),
                teacher.getClass().getInterfaces(),
                new RepresentativeHandler(teacher)
        );

        //学生交作业
        System.out.println("学生:交作业");
        representative.doSomething();

        System.out.println("---------------------------------------------------------------------------------");

        //学生交作业2
        System.out.println("学生:交作业");
        representative.doOtherThing();
    }
}

        结果:

学生:交作业
课代表:收作业
老师:批改作业
课代表:发作业
---------------------------------------------------------------------------------
学生:交作业
课代表:收作业
老师:查看作业
课代表:发作业

        看,如果用的是静态代理,我们原本是不是要在代理类里去实现doOtherThing方法,用动态代理,无论增加多少个方法,都不用再去一个个实现。

        6、最后,我们输出打印类名:

public class JdkDynamicTest {
    public static void main(String[] args) {
        //老师
        Person teacher = new Teacher();

        //课代表
        Person representative = (Person)Proxy.newProxyInstance(
                teacher.getClass().getClassLoader(),
                teacher.getClass().getInterfaces(),
                new RepresentativeHandler(teacher)
        );

        System.out.println(teacher + ":" + teacher.getClass().getName());

        System.out.println("---------------------------------------------------------------------------------");

        System.out.println(representative + ":" + representative.getClass().getName());
    }
}

        结果:

com.example.study.proxy.test.Teacher@1fb3ebeb:com.example.study.proxy.test.Teacher
---------------------------------------------------------------------------------
课代表:收作业
课代表:发作业
com.example.study.proxy.test.Teacher@1fb3ebeb:jdk.proxy1.$Proxy0

      可以看到,比较手动编码的类,动态代理类类名有$标识,在Java中,以$符号开头的类名通常是编译器或运行时系统自动生成的类的命名约定。

3、扩展内容

        看完代码实现,应该基本了解了jdk动态代理的简单使用,我们继续做些额外的扩展。

1、原理

  • Proxy.newInstance方法:

   

        首先,接口内部通过参数传入的类加载器和接口列表,创建了一个构造函数cons,因此,jdk动态代理是基于接口实现的,被代理类必须实现接口。而cons.newInstance()底层是Constructor.newInstance(),利用了Java反射机制创建一个指定类的新实例。

  • 2、InvocationHandler接口invoke方法:

  • proxy:代理实例,即方法被调用的对象。
  • method:Method实例,对应于代理实例上调用的接口方法。
  • args:对象数组,包含代理实例上方法调用时传入的参数值。

        每次通过代理对象调用方法时,JVM就会自动委托给这个InvocationHandler实例的invoke方法执行,而在invoke方法内部,通常会利用Method对象(作为参数传递进来的method)和java.lang.reflect.Method类的API(如invoke方法)来调用目标对象的实际方法。    

2、持久化框架中的映射器代理的简单实现

  • 映射器代理类
public class MapperProxy<T> implements InvocationHandler, Serializable {

  private static final long serialVersionUID = -6424540398559729838L;

  //数据库会话对象
  private final SqlSession sqlSession;

  //要代理的Mapper接口
  private final Class<T> mapperInterface;

  //缓存,用于存储每个方法对应的MapperMethod对象。
  //MapperMethod类是MyBatis中处理映射器方法的类。它根据不同的SQL命令类型(INSERT、UPDATE、DELETE、SELECT)执行相应的操作,并根据方法的返回类型处理结果。它还处理了参数映射、结果映射和结果处理器的逻辑。
  private final Map<Method, MapperMethod> methodCache;

  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    //过滤Object中通用的方法,不代理
    if (Object.class.equals(method.getDeclaringClass())) {
      try {
        return method.invoke(this, args);
      } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
      }
    }

    //缓存中查对应方法的MapperMethod对象,不存在创建并放入缓存
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }

}
  • 映射器代理工厂
public class MapperProxyFactory<T> {

  //要创建代理对象的Mapper接口
  private final Class<T> mapperInterface;

  //缓存Mapper方法与对应的MapperMethod对象的映射关系
  private Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();

  public MapperProxyFactory(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }

  public Class<T> getMapperInterface() {
    return mapperInterface;
  }

  public Map<Method, MapperMethod> getMethodCache() {
    return methodCache;
  }

  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

  //创建一个MapperProxy对象
  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

}
  • 返回代理类
//返回代理类
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }

4、总结

        了解完jdk动态代理,相比静态代理确实方便了很多,但是这种代理方式本质是基于接口实现的,所以无法摆脱接口的限制,如果想要代理的类没有具体实现的接口,那要怎么办呢,下个章节我们继续讲讲CGLib 动态代理......        

  • 20
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值