hutool中@Alias

2022-08-21 11:24:22 浏览数 (2)

我们可以使用hutool中的@Alias注解去给bean取别名,例如:

代码语言:javascript复制
@Data
public static class BeanWithAlias {
	@Alias("name")
	private String value1;
	@Alias("age")
	private Integer value2;
}

然后别名不仅能在BeanUtil.copyProperties中使用,还可以在JSONUtil中使用:

代码语言:javascript复制
final BeanWithAlias beanWithAlias = new BeanWithAlias();
beanWithAlias.setValue1("张三");
beanWithAlias.setValue2(35);

final JSONObject jsonObject = JSONUtil.parseObj(beanWithAlias);
Assert.assertEquals("张三", jsonObject.getStr("name"));
Assert.assertEquals(new Integer(35), jsonObject.getInt("age"));

JSONObject json = JSONUtil.createObj()
		.set("name", "张三")
		.set("age", 35);
final BeanWithAlias bean = JSONUtil.toBean(Objects.requireNonNull(json).toString(), BeanWithAlias.class);
Assert.assertEquals("张三", bean.getValue1());
Assert.assertEquals(new Integer(35), bean.getValue2());

这个注解还是非常方便的

0 人点赞