BeanUtil toBean 转换错误
iszhangsc opened this issue · 6 comments
iszhangsc commented
版本情况
JDK版本: jdk17
hutool版本: 5.8.27
问题描述(包括截图)
- 复现代码
public class SourceBean {
private Long id;
private Boolean isUserFollowing;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Boolean getUserFollowing() {
return isUserFollowing;
}
public void setUserFollowing(Boolean userFollowing) {
isUserFollowing = userFollowing;
}
}
public class TagetBean {
private Long id;
private Boolean isUserFollowing;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Boolean getUserFollowing() {
return isUserFollowing;
}
public void setUserFollowing(Boolean userFollowing) {
isUserFollowing = userFollowing;
}
}
public static void main(String[] args) {
SourceBean source = new SourceBean();
source.setId(111L);
source.setUserFollowing(true);
// spring bean 方式拷贝是有isUserFollowing 值的
TargetBean springTargetBean = new TargetBean();
BeanUtils.copyProperties(source, springTargetBean);
// hutool bean 方式拷贝 没有 isUserFollowing 值
TargetBean hutoolTargetBean = new TargetBean();
BeanUtil.copyProperties(source, hutoolTargetBean);
}
kissthisrain commented
iszhangsc commented
这个方法名称是使用IDEA自动生成的。 按照你的这个解决办法 我如果后面使用到了 boolean 类型 全都需要自己手动添加 get set 方法?
kissthisrain commented
iszhangsc commented
这样的话,团队的所有人都去进行修改,为什么不按照流行的 spring
这类框架来进行拷贝呢? 是代码历史原因,还是出于什么原因呢?
kissthisrain commented
这样的话,团队的所有人都去进行修改,为什么不按照流行的
spring
这类框架来进行拷贝呢? 是代码历史原因,还是出于什么原因呢?
主要是is开头的布尔型变量本身就是不太规范的写法,JSON 序列化也可能会出现问题
looly commented
@iszhangsc 这里不匹配是因为Hutool存在一个字段和getter匹配检查的功能,这个Spring没有。
在Spring中,只读取getter和setter方法,而不去判断字段,你可以试下,isUserFollowing
换成任意名字,Spring也是照样可以的。
如果只判断方法而不去匹配字段,就存在误判问题。比如你自定义了一个方法,叫做getXXXX,但是并没有对应字段,那这个方法要不要读取呢?Hutool的策略是不读取。
Spring的方法存在第二个问题,就是假设你有两个字段:isUserFollowing
和userFollowing
那你的getter方法该如何定义呢?因此,为了解决这些问题,Hutool专门做了字段匹配功能,来避免这些问题。
欢迎进一步讨论。