mybatis之MetaObject
MetaObject
元数据对象,底层肯定是反射,通过反射来进行设置值。
这个可以来操作对象中的属性,哪怕是组合方式,无论有多少层,这个都可以来进行操作。
举例如下所示:
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private List<String> hobbies;
private Boolean flag;
private Map<String,Object> objectMap;
@Override
public String toString() {
return "Author{" +
"id=" + id +
", hobbies=" + hobbies +
", flag=" + flag +
", objectMap=" + objectMap +
'}';
}
}
public class UserInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Author author;
@Override
public String toString() {
return "UserInfo{" +
"name='" + name + '\'' +
", author=" + author +
'}';
}
}
MetaObject来进行演示:
直接给属性赋值
@Test
public void testOne(){
UserInfo userInfo = new UserInfo();
MetaObject metaObject = MetaObject.forObject(userInfo, SystemMetaObject.DEFAULT_OBJECT_FACTORY,SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,SystemMetaObject.NULL_META_OBJECT.getReflectorFactory());
metaObject.setValue("author.id",666);
System.out.println(userInfo);
}
输出结果:
UserInfo{name='null', author=Author{id=666, hobbies=null, flag=null, objectMap=null}}
即使没有创建对象,但是使用MetaObject,也能够帮我们来创建这个类中的类的对象。
根据驼峰命名来查找得到对应的属性
@Test
public void testTwo(){
UserInfo userInfo = new UserInfo();
MetaObject metaObject = MetaObject.forObject(userInfo, SystemMetaObject.DEFAULT_OBJECT_FACTORY,SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,SystemMetaObject.NULL_META_OBJECT.getReflectorFactory());
// 支持驼峰命名
String objectMmap = metaObject.findProperty("author.object_map", true);
System.out.println(objectMmap);
}
对应输出:
author.objectMap
操作子属性中的数组
@Test
public void testFour(){
UserInfo userInfo = new UserInfo();
MetaObject metaObject = MetaObject.forObject(userInfo, SystemMetaObject.DEFAULT_OBJECT_FACTORY,SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,SystemMetaObject.NULL_META_OBJECT.getReflectorFactory());
ArrayList<String> strings = new ArrayList<>();
strings.add("666");
strings.add("777");
strings.add("888");
metaObject.setValue("author.hobbies",strings);
System.out.println(metaObject.getValue("author.hobbies[2]"));
}
输出:
888
操作子属性中的map
@Test
public void testThree(){
UserInfo userInfo = new UserInfo();
MetaObject metaObject = MetaObject.forObject(userInfo, SystemMetaObject.DEFAULT_OBJECT_FACTORY,SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,SystemMetaObject.NULL_META_OBJECT.getReflectorFactory());
HashMap<String, Object> stringObjectHashMap = new HashMap<>();
stringObjectHashMap.put("hello",777);
stringObjectHashMap.put("world",888);
metaObject.setValue("author.objectMap",stringObjectHashMap);
System.out.println(metaObject.getValue("author.objectMap[hello]"));
}
打印:
777
从理论中来,到实践中去,最终回归理论