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. docker gitlab 如何git clone?2. java报错Communications link failure 该如何解决?3. android - 项目时间长了,字符串文件strings有的字符串可能是多余的,有没有办法快速检测那些是没用的?4. javascript - 怎么看网站用了什么技术框架?5. mysql - 用PHPEXCEL将excel文件导入数据库数据5000+条,本地数据库正常,线上只导入15条,没有报错,哪里的问题?6. angular.js使用$resource服务把数据存入mongodb的问题。7. 刷新页面出现弹框8. 关于Android权限的获取问题,大家遇到过这样的情况嘛?9. angular.js - angularJs ngRoute怎么在路由传递空字符串及用ng-switch取得10. PC 手机兼容的 编辑器
