Hutool的BeanUtil常用使用方式

一,hutool中beanUtil的常见三种使用方式

  1. BeanUtil.fillBeanWithMap 使用Map填充bean
HashMap<String, Object> map = CollUtil.newHashMap();
map.put("name", "Joe");
map.put("age", 12);
map.put("openId", "DFDFSDFWERWER");
SubPerson person = BeanUtil.fillBeanWithMap(map, new SubPerson(), false);
  1. BeanUtil.beanToMap方法则是将一个Bean对象转为Map对象
SubPerson person = new SubPerson();
person.setAge(14);
person.setOpenid("11213232");
person.setName("测试A11");
person.setSubName("sub名字");
 
Map<String, Object> map = BeanUtil.beanToMap(person);
  1. BeanUtil.copyProperties方法同样提供一个CopyOptions参数用于自定义属性复制。
SubPerson p1 = new SubPerson();
p1.setSlow(true);
p1.setName("测试");
p1.setSubName("sub测试");
 
Map<String, Object> map = MapUtil.newHashMap();
 
BeanUtil.copyProperties(p1, map);
  1. Alias, 通过注解可以给bean的字段设置别民
// Lombok注解
@Getter
@Setter
public static class SubPersonWithAlias {
          
   
    @Alias("aliasSubName")
    private String subName;
    private Boolean slow;
经验分享 程序员 微信小程序 职场和发展