国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

java - 將list<bean> 強轉(zhuǎn)成另一種bean的list。

瀏覽:105日期:2023-11-29 16:39:13

問題描述

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);

報錯不可轉(zhuǎn)換的類型,DataBean是個內(nèi)部靜態(tài)類。C++里面有reinterpret_cast可以強轉(zhuǎn),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 + ’}’;} }}

java - 將list<bean> 強轉(zhuǎn)成另一種bean的list。

所以如果 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);}

當然,需要注意的一點是,這是使用反射實現(xiàn)的,效率要比直接寫 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:

強轉(zhuǎn)只能父類轉(zhuǎn)子類,你這就老實點一個個字段set過去就好了

回答4:

樓主學習一下 Java 的類型轉(zhuǎn)換啊。這種條件下,不能強轉(zhuǎn)的。

標簽: java
相關(guān)文章:
主站蜘蛛池模板: 隆尧县| 南陵县| 武陟县| 新丰县| 上高县| 抚顺县| 广德县| 台湾省| 基隆市| 稻城县| 冕宁县| 洱源县| 姜堰市| 杨浦区| 金秀| 新兴县| 北票市| 桦甸市| 伊吾县| 定陶县| 农安县| 宁津县| 宜昌市| 都兰县| 江阴市| 万全县| 乌审旗| 通化县| 芮城县| 西盟| 栾城县| 霍城县| 连南| 彭泽县| 元谋县| 垦利县| 连云港市| 桃园县| 兴安县| 东安县| 石河子市|