java - 将list<bean> 强转成另一种bean的list。
问题描述
public static class DataBean { private int value; private BigDecimal name;}public class ChartData { private Integer time; private BigDecimal result;}
我需要类似于如下的操作,
List<ChartData> data = getdata();List<SeriesBean.DataBean> yValue = data.stream().map(item -> (SeriesBean.DataBean) item);
报错不可转换的类型,DataBean是个内部静态类。C++里面有reinterpret_cast可以强转,java应该有相应的方法的
问题解答
回答1:Apache Commons 的 BeanUtils 和 Spring 的 BeanUtils 都有提供 copyProperties 方法,作用是将一个对象的属性的值赋值给另外一个对象,但前提是两个对象的属性类型且 名字 相同。
比如使用 Apache Commons 的 BeanUtils:
import java.math.BigDecimal;import org.apache.commons.beanutils.BeanUtils;public class TestBeanUtils { public static void main(String[] args) throws Exception {ChartData src = new ChartData(1, BigDecimal.valueOf(123));DataBean dest = new DataBean();BeanUtils.copyProperties(dest, src);System.out.println(src);System.out.println(dest); } public static class DataBean {private int time;private BigDecimal result;public int getTime() { return time;}public void setTime(int time) { this.time = time;}public BigDecimal getResult() { return result;}public void setResult(BigDecimal result) { this.result = result;}@Overridepublic String toString() { return 'DataBean{' + 'time=' + time + ', result=' + result + ’}’;} } public static class ChartData {private Integer time;private BigDecimal result;public ChartData(Integer time, BigDecimal result) { this.time = time; this.result = result;}public Integer getTime() { return time;}public BigDecimal getResult() { return result;}public void setTime(Integer time) { this.time = time;}public void setResult(BigDecimal result) { this.result = result;}@Overridepublic String toString() { return 'ChartData{' + 'time=' + time + ', result=' + result + ’}’;} }}
所以如果 ChartData 和 DataBean 的属性名称一致,你的代码可以这样写(就不用挨个属性的写 setter 方法了):
List<ChartData> data = getdata();List<DataBean> yValue = new ArrayList<>(data.size());for (ChartData item : data) { DataBean bean = new DataBean(); BeanUtils.copyProperties(bean, item); yValue.add(bean);}
当然,需要注意的一点是,这是使用反射实现的,效率要比直接写 setter 方法要低一些。
回答2:List<DataBean> yValue = data.stream().map(item -> { DataBean bean = new DataBean(); bean.setName(item.getResult()); bean.setValue(item.getTime()); return bean;}).collect(Collectors.toList());回答3:
强转只能父类转子类,你这就老实点一个个字段set过去就好了
回答4:楼主学习一下 Java 的类型转换啊。这种条件下,不能强转的。
相关文章:
1. windows误人子弟啊2. php传对应的id值为什么传不了啊有木有大神会的看我下方截图3. 如何用笔记本上的apache做微信开发的服务器4. python - linux 下用wsgifunc 运行web.py该如何修改代码5. 关于mysql联合查询一对多的显示结果问题6. 实现bing搜索工具urlAPI提交7. 冒昧问一下,我这php代码哪里出错了???8. mysql优化 - MySQL如何为配置表建立索引?9. MySQL主键冲突时的更新操作和替换操作在功能上有什么差别(如图)10. 数据库 - Mysql的存储过程真的是个坑!求助下面的存储过程哪里错啦,实在是找不到哪里的问题了。
