目录
-
BeanUtils.copyProperties()拷贝id属性失败
- 部分代码如下
- 解决方法
-
BeanUtils.copyProperties 出错
BeanUtils.copyProperties()拷贝id属性失败
po类中id有值,但是使用BeanUtils.copyProperties()拷贝出的vo类id属性为null,检查后发现是因为po继承的父类声明了一个泛型。
部分代码如下
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public abstract class AbstractEntity<ID extends Serializable> implements Serializable {
protected ID id;
/**创建人*/
protected ID createdBy;
/**创建时间*/
protected Date createdTime;
/**最后一次修改人*/
protected ID lastModifiedBy;
/**最后一次修改时间*/
protected Date lastModifiedTime;
public void setId(ID id) {
this.id = id;
}
public ID getId() {
return this.id;
}
|
查看BeanUtils.copyProperties()源码中有一段判断如下:
?| 1 |
if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType()))
|
当执行到获取vo类的writeMethod即setId()参数类型,结果是Long类型,而po类的readMethod即getId()返回值类型获取到的结果却是Serializable所以BeanUtils认为属性类型不同,所以不会拷贝id属性。
解决方法
暂不清楚po类extends AbstractEntity<Long>后为什么读取到的类型不是Long而是父类型Serializable,暂时先不用泛型,把id类型直接定义为Long,问题解决~
BeanUtils.copyProperties 出错
注意:属性复制,不同jar中的方法,用法不一样!
Spring 包(org.springframework.beans)中
?| 1 |
BeanUtils.copyProperties(A,B);
|
是A中的值赋值给B
Apache 包(org.apache.commons.beanutils)中(常用)
?| 1 |
BeanUtils.copyProperties(A,B);
|
是B中的值赋值给A
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/noob9527/article/details/90168244








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。