想问一下,子类继承父类之后,如果使用BeanUtils.copyProperties(),能将父类的属性值拷贝到子类中吗?如果没问题的话,我这里怎么没有拷贝成功
下面是我的代码
public class Items {
private Integer id;
private String name;
private Float price;
private String pic;
private Date createtime;
private String detail;
下面是get()和set()方法
}
public class ItemsCustom extends Items {
@Override
public String toString() {
return "ItemsCustom [
getId()=" + getId()
+ ", getName()=" + getName()
+ ", getPrice()=" + getPrice()
+ ", getPic()=" + getPic()
+ ", getCreatetime()=" + getCreatetime()
+ ", getDetail()="
+ getDetail()
+ "]";
}
这是测试方法内容:
Items items = itemsMapper.selectByPrimaryKey(id);
//中间对商品信息进行业务处理
//.....
//返回ItemsCustom
ItemsCustom itemsCustom = new ItemsCustom();
//将items的属性值拷贝到itemsCustom
BeanUtils.copyProperties(items,itemsCustom);
System.out.println(itemsCustom);
运行结果是:ItemsCustom [getId()=null, getName()=null, getPrice()=null, getPic()=null, getCreatetime()=null, getDetail()=null]
子类并没有拷贝父类的属性值。不知道怎么回事,请大家帮忙
父类属性用protected
使用hutool工具包的BeanUtil
不应该啊,我测试的结果是没问题,代码如下:
public class Father {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Son extends Father{
}
/**
* @Title:
* @Author:wangchenggong
* @Date 2020/10/3 9:16
* @Description
* @Version
*/
public class TestBeanCopy {
public static void main(String[] args) {
Father father = new Father();
father.setAge(18);
father.setName("张三");
Son son = new Son();
BeanUtils.copyProperties(father,son);
System.out.println(son.getName()+","+son.getAge());//张三,18
}
}