java - 将list<bean> 强转成另一种bean的list。

查看:980
本文介绍了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应该有相应的方法的

解决方案

Apache CommonsBeanUtilsSpringBeanUtils 都有提供 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;
        }

        @Override
        public 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;
        }

        @Override
        public String toString() {
            return "ChartData{" + "time=" + time + ", result=" + result + '}';
        }

    }

}


所以如果 ChartDataDataBean 的属性名称一致,你的代码可以这样写(就不用挨个属性的写 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 方法要低一些。

这篇关于java - 将list&lt;bean&gt; 强转成另一种bean的list。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆