zl程序教程

您现在的位置是:首页 > 

当前栏目

hutool中@Alias

Alias hutool
2023-06-13 09:11:17 时间

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

@Data
public static class BeanWithAlias {
	@Alias("name")
	private String value1;
	@Alias("age")
	private Integer value2;
}

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

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());

这个注解还是非常方便的