mybatis基础支持层-反射模块-04

反射模块:MetaClass/ObjectWrapper/MetaObject

Posted by Claire on June 21, 2020

Mybatis基础支持层-反射模块:MetaClass

一、MetaClass

MetaClass是对类级别元信息的封装和处理 MetaClass 通过Reflector和PropertyTokenizer组合使用,实现对复杂的属性表达式解析,并实现了获取指定属性描述信息的功能。 依赖reflector获取属性名,中间涉及属性表达式解析,递归拆解,返回类型的判定

  private MetaClass(Class<?> type, ReflectorFactory reflectorFactory) {
    this.reflectorFactory = reflectorFactory;
    this.reflector = reflectorFactory.findForClass(type);
  }

    public static MetaClass forClass(Class<?> type, ReflectorFactory reflectorFactory) {
    return new MetaClass(type, reflectorFactory);
  }

1.findProperty

public String findProperty(String name) {
    StringBuilder prop = buildProperty(name, new StringBuilder());
    return prop.length() > 0 ? prop.toString() : null;
  }

  private StringBuilder buildProperty(String name, StringBuilder builder) {
    //解析字符串--属性表达式,获取parent 和 child
    PropertyTokenizer prop = new PropertyTokenizer(name);
    if (prop.hasNext()) {
      String propertyName = reflector.findPropertyName(prop.getName());
      if (propertyName != null) {
        builder.append(propertyName);
        builder.append(".");
        //为该属性创建对应的MetaClass对象
        MetaClass metaProp = metaClassForProperty(propertyName);
        metaProp.buildProperty(prop.getChildren(), builder);
      }
    } else {//递归出口
      String propertyName = reflector.findPropertyName(name);
      if (propertyName != null) {
        builder.append(propertyName);
      }
    }
    return builder;
  }

2.hasGetter

  • 示例:products[0].id;
  1. name product
  2. indexName products[0]
  3. index = 0
  4. children = name
    public boolean hasGetter(String name) {
    PropertyTokenizer prop = new PropertyTokenizer(name);
    //解析属性字符串
    if (prop.hasNext()) {
      //属性有get方法
      if (reflector.hasGetter(prop.getName())) {
        MetaClass metaProp = metaClassForProperty(prop);
        return metaProp.hasGetter(prop.getChildren());
      } else {
        return false;
      }
    } else {
      return reflector.hasGetter(prop.getName());
    }
  }

   private MetaClass metaClassForProperty(PropertyTokenizer prop) {
    Class<?> propType = getGetterType(prop);
    return MetaClass.forClass(propType, reflectorFactory);
  }

private Class<?> getGetterType(PropertyTokenizer prop) {
    //查找返回类型
    Class<?> type = reflector.getGetterType(prop.getName());
    //属性中是否用[]指明了下标
    if (prop.getIndex() != null && Collection.class.isAssignableFrom(type)) {
      //如果type是集合子类
      //依靠TypeParameterResolver.resolveReturnType(method, reflector.getType());获取属性类型
      Type returnType = getGenericGetterType(prop.getName());
      //针对泛型类别进行处理
      if (returnType instanceof ParameterizedType) {
        //返回值是参数化的
        Type[] actualTypeArguments = ((ParameterizedType) returnType).getActualTypeArguments();
        //获取真实类型
        if (actualTypeArguments != null && actualTypeArguments.length == 1) {
          //泛型类型
          returnType = actualTypeArguments[0];
          //属于类
          if (returnType instanceof Class) {
            type = (Class<?>) returnType;
          } else if (returnType instanceof ParameterizedType) {
            //参数化
            type = (Class<?>) ((ParameterizedType) returnType).getRawType();
          }
        }
      }
    }
    return type;
  }

   private Type getGenericGetterType(String propertyName) {
    try {
      //获取方法的get方法调用
      Invoker invoker = reflector.getGetInvoker(propertyName);
      if (invoker instanceof MethodInvoker) {
        //属于方法调用
        Field declaredMethod = MethodInvoker.class.getDeclaredField("method");
        declaredMethod.setAccessible(true);
        Method method = (Method) declaredMethod.get(invoker);
        return TypeParameterResolver.resolveReturnType(method, reflector.getType());
      } else if (invoker instanceof GetFieldInvoker) {
        // get属性方法
        Field declaredField = GetFieldInvoker.class.getDeclaredField("field");
        declaredField.setAccessible(true);
        Field field = (Field) declaredField.get(invoker);
        return TypeParameterResolver.resolveFieldType(field, reflector.getType());
      }
    } catch (NoSuchFieldException | IllegalAccessException e) {
      // Ignored
    }
    return null;
  }

二、ObjectWrapper



           ObjectWrapper    <------------ ObjectWrapperFactory
       |-------|---------|                          |
       |                                            |
    BaseWrapper   CollectionWrapper  DefaultObjectWrapperFactory
       |
  |---------------|
 BeanWrapper  MapWrapper

处理对象级别的信息处理,对对象进行包装,信息抽象

public interface ObjectWrapper {

  //获取属性参数,如果普通bean,调用getter,如果是集合,则获取执行下标的值
  Object get(PropertyTokenizer prop);

  //设置属性参数,如果普通bean,调用setter,如果是集合,则设置执行下表的值
  void set(PropertyTokenizer prop, Object value);

  //查找属性表达式中的属性, useCamelCaseMapping是否忽略下划线
  String findProperty(String name, boolean useCamelCaseMapping);

  //获取可写属性列表
  String[] getGetterNames();

  //获取可读属性列表
  String[] getSetterNames();

  //获取属性表达式中指定属性的参数类型
  Class<?> getSetterType(String name);

  //获取属性表达式中指定属性的返回值类型
  Class<?> getGetterType(String name);

  //判断属性是否有setter方法
  boolean hasSetter(String name);

  //判断属性是否有getter属性
  boolean hasGetter(String name);

  //为属性表达式指定属性设置MetaObject对象
  MetaObject instantiatePropertyValue(String name, PropertyTokenizer prop, ObjectFactory objectFactory);

  //判断是否是集合
  boolean isCollection();

  //为集合添加元素
  void add(Object element);

  //为集合添加元素
  <E> void addAll(List<E> element);

}

1.ObjectWrapperFactory

构建ObjectWrapper对象

public interface ObjectWrapperFactory {

  //判断是否存在某对象的ObjectWrapper
  boolean hasWrapperFor(Object object);

  //获取ObjectWrapper
  ObjectWrapper getWrapperFor(MetaObject metaObject, Object object);

}

//jar中给出的一个默认的实现,没有给出可用的实现,因而需要自定义实现一个
public class DefaultObjectWrapperFactory implements ObjectWrapperFactory {

  @Override
  public boolean hasWrapperFor(Object object) {
    return false;
  }

  @Override
  public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
    throw new ReflectionException("The DefaultObjectWrapperFactory should never be called to provide an ObjectWrapper.");
  }

}
//自定义实现ObjectWrapperFactory,主要解决两个:判断是否存在object wrapper, 获取对象的Object wrapper对象
public class CustomObjectWrapperFactory implements ObjectWrapperFactory {

  @Override
  public boolean hasWrapperFor(Object object) {
    return object.getClass().equals(CustomCollection.class);
  }

  @Override
  public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
    return new CustomObjectWrapper((CustomCollection) object);
  }

}

2.BeseWrapper

//通过MetaObject获取指定属性的value
protected Object resolveCollection(PropertyTokenizer prop, Object object){...}

//获取指定下表是属性的值
protected Object getCollectionValue(PropertyTokenizer prop, Object collection){...}

//设定值
protected void setCollectionValue(PropertyTokenizer prop, Object collection, Object value){...}

3.BeanWrapper

public class BeanWrapper extends BaseWrapper {
  //添加了对象
  private final Object object;
  //添加对象元数据
  private final MetaClass metaClass;
  ...


  @Override
  public Object get(PropertyTokenizer prop) {
    if (prop.getIndex() != null) {
      Object collection = resolveCollection(prop, object);
      return getCollectionValue(prop, collection);
    } else {
      return getBeanProperty(prop, object);
    }
  }

}

MapWrapper 与 CollectionWrapper都与BeanMapper类似,内部绑定了一个集合或者一个Map

三、MetaObject

集合属性表达式解析,ObjectWrapper,reflector,可以对Bean的属性进行获取和设置

 //对象无法通过new的方式创建
  private MetaObject(Object object, ObjectFactory objectFactory, ObjectWrapperFactory objectWrapperFactory, ReflectorFactory reflectorFactory) {
    this.originalObject = object;
    this.objectFactory = objectFactory;
    this.objectWrapperFactory = objectWrapperFactory;
    this.reflectorFactory = reflectorFactory;

    //判断object的所属类型,设置objectwrapper对应的实现
    if (object instanceof ObjectWrapper) {
      //若原始类型就是object wrapper 就直接赋值
      this.objectWrapper = (ObjectWrapper) object;
    } else if (objectWrapperFactory.hasWrapperFor(object)) {
      //如果能够由 objectWrapperFactory创建wrapper则优先创建
      this.objectWrapper = objectWrapperFactory.getWrapperFor(this, object);
    } else if (object instanceof Map) {
      //匹配Map
      this.objectWrapper = new MapWrapper(this, (Map) object);
    } else if (object instanceof Collection) {
      //匹配Collection
      this.objectWrapper = new CollectionWrapper(this, (Collection) object);
    } else {
      //最后交给BeanWrapper
      this.objectWrapper = new BeanWrapper(this, object);
    }
  }

  //提供静态方法,进行MetaObject的创建
  public static MetaObject forObject(Object object, ObjectFactory objectFactory, ObjectWrapperFactory objectWrapperFactory, ReflectorFactory reflectorFactory) {
    if (object == null) {
      //对象为null
      return SystemMetaObject.NULL_META_OBJECT;
    } else {
      return new MetaObject(object, objectFactory, objectWrapperFactory, reflectorFactory);
    }
  }

//根据属性名称获取属性对应的MetaObject对象
    public MetaObject metaObjectForProperty(String name) {
    Object value = getValue(name);
    return MetaObject.forObject(value, objectFactory, objectWrapperFactory, reflectorFactory);
  }

//主要的方法之一,获取属性值
   public Object getValue(String name) {
    //解析属性表达式
    PropertyTokenizer prop = new PropertyTokenizer(name);
    if (prop.hasNext()) {
      //对应index的meta obejct对象
      MetaObject metaValue = metaObjectForProperty(prop.getIndexedName());
      if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
        return null;
      } else {
        //递归处理子表达式
        return metaValue.getValue(prop.getChildren());
      }
    } else {
      //出口调用ObjectWrapper(对应实现)的get方法给出指定属性的内容
      return objectWrapper.get(prop);
    }
  }