Mybatis MetaObject和ObjectWrapper设计概念

ObjectWrapper

该类的作用是对象的包装,对对象属性的操作,其行为有

BaseWrapper

具备了MetaObject,对象包装的公共父类,主要处理集合类型

BeanWrapper

具备了储存对象的Object和MetaClass

@Override
public Object get(PropertyTokenizer prop) {
    if (prop.getIndex() != null) {
        // 使用MetaObject逐级实例化集合对象
        Object collection = resolveCollection(prop, object);
        // 使用MetaObject获得Value
        return getCollectionValue(prop, collection);
    } else {
        return getBeanProperty(prop, object);
    }
}

MetaObject

private final Object originalObject;
private final ObjectWrapper objectWrapper;
private final ObjectFactory objectFactory;
private final ObjectWrapperFactory objectWrapperFactory;
private final ReflectorFactory reflectorFactory;

private MetaObject(Object object, ObjectFactory objectFactory, ObjectWrapperFactory objectWrapperFactory, ReflectorFactory reflectorFactory) {
    this.originalObject = object;
    this.objectFactory = objectFactory;
    this.objectWrapperFactory = objectWrapperFactory;
    this.reflectorFactory = reflectorFactory;

    // 根据originalObject的类型实例化具体的ObjectMapper,将MetaObject自己注入进去,委派模式
    if (object instanceof ObjectWrapper) {
      this.objectWrapper = (ObjectWrapper) object;
    } else if (objectWrapperFactory.hasWrapperFor(object)) {
      this.objectWrapper = objectWrapperFactory.getWrapperFor(this, object);
    } else if (object instanceof Map) {
      this.objectWrapper = new MapWrapper(this, (Map) object);
    } else if (object instanceof Collection) {
      this.objectWrapper = new CollectionWrapper(this, (Collection) object);
    } else {
      this.objectWrapper = new BeanWrapper(this, object);
    }
}

获得初始对象的属性值通过ObjectWrapper并可能委派给MetaObject来获得。

 

posted @ 2018-10-22 11:20  BINGJJFLY  阅读(3450)  评论(0编辑  收藏  举报