跳到主要内容

BeanUtil - Bean 工具

← 返回文档导航


BeanUtil 提供 Bean 属性复制、Bean 与 Map 互转功能,配合 @SetValue 注解实现扁平 Bean 与嵌套 JSON 的双向映射。

copyAsSource — Bean 作为数据源

将 Bean 的属性复制到 JSONMap,支持 @SetValue 注解映射到嵌套路径:

JSONMap target = new JSONMap();
BeanUtil.copyAsSource(user, target, false); // 全部字段
BeanUtil.copyAsSource(user, target, true); // 只复制 @SetValue 字段

copyAsTarget — Map/JSONMap 作为数据源

User user = new User();
BeanUtil.copyAsTarget(data, user); // JSONMap → Bean

copyProperties — Bean 属性复制

UserVO vo = new UserVO();
BeanUtil.copyProperties(user, vo); // User → UserVO

@SetValue 示例

@Data
public class UserForm {
private String name;
@SetValue("profile")
private String phone;
@SetValue("profile")
private String address;
}

// 扁平 Bean → 嵌套 JSON
UserForm form = new UserForm();
form.setName("张三");
form.setPhone("13800138000");

JSONMap json = new JSONMap();
BeanUtil.copyAsSource(form, json, false);
// → {"name":"张三","profile":{"phone":"13800138000"}}

// 嵌套 JSON → 扁平 Bean
BeanUtil.copyAsTarget(json, form);
// form.phone = "13800138000"

详见 4.1 @SetValue 注解映射

注意事项

  • 属性名必须完全匹配(区分大小写)
  • ignoreNull = true 时跳过 null 值
  • 简单类型自动转换(String → Integer 等),复杂类型可能失败

← 上一节:StringUtils | 返回文档导航 | 下一节:Cache →