2013-10-11 87 views
2

我知道BeanUtils可以将单个对象复制到其他对象。BeanUtils copyProperties复制Arraylist

是否可以复制一个数组列表。

例如:

FromBean fromBean = new FromBean("fromBean", "fromBeanAProp", "fromBeanBProp"); 
ToBean toBean = new ToBean("toBean", "toBeanBProp", "toBeanCProp"); 
BeanUtils.copyProperties(toBean, fromBean); 

如何实现这一目标?

List<FromBean > fromBeanList = new ArrayList<FromBean >(); 
List<ToBean > toBeanList = new ArrayList<ToBean >(); 
BeanUtils.copyProperties(toBeanList , fromBeanList); 

它不适合我。谁能帮帮我吗。

在此先感谢。

回答

4

如果你有平等的两个列表大小,那么你可以做以下

for (int i = 0; i < fromBeanList.size(); i++) { 
    BeanUtils.copyProperties(toBeanList.get(i), fromBeanList.get(i)); 
} 
+0

亚现在我做到了这一点但我想知道一次完全复制谢谢 –

0

BeanUtils.copyProperties,它只复制同名的属性。所以,在ArrayList的情况下,你不能这样做。

根据文档:从原点豆到目的地豆的 所有情况下的属性名称是相同的

复制属性值。

1

,你可以尝试这样的事情

for(int i=0; i<fromBeanList.size(); i++){ 
    BeanUtils.copyProperties(toBeanList.get(i) , fromBeanList.get(i)); 
} 

希望这有助于..

哎呀它现在已经有人解释了..

反正试试吧。

3

如果你有数据和列表目的地列表起源空的,解决的办法是:

List<Object> listOrigin (with data) 
    List<Object> listDestination= new ArrayList<Object>(); 

    for (Object source: listOrigin) { 
     Object target= new Object(); 
     BeanUtils.copyProperties(source , target); 
     listDestination.add(target); 
    } 
+0

这一个实际上是正确的实现,而不是接受的答案。 –

0

你可以做的是写自己的泛型类的副本。

class CopyVector<S, T> { 
    private Class<T> targetType; 
    CopyVector(Class<T> targetType) { 
     this.targetType = targetType; 
    } 
    Vector<T> copy(Vector<S> src) { 
     Vector<T> target = new Vector<T>(); 
     for (S s : src) { 
      T t = BeanUtils.instantiateClass(targetType); 
      BeanUtils.copyProperties(s, t); 
      target.add(t); 
     } 
     return target; 
    } 
} 

进一步的做法还是使List类型为通用 - 假设您要复制Vectors。