我想知道如何在Java中使用Dozer将一种类型的列表转换为另一种类型的数组。这两种类型都具有相同的属性名称/类型。例如,考虑这两个类。
public class A{
    private String test = null;
    public String getTest(){
      return this.test
    }
    public void setTest(String test){
      this.test = test;
    }
}
public class B{
    private String test = null;
    public String getTest(){
      return this.test
    }
    public void setTest(String test){
      this.test = test;
    }
}我试过了,但没有成功。
List<A> listOfA = getListofAObjects();
Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();
B[] bs = mapper.map(listOfA, B[].class);我还尝试过使用CollectionUtils类。
CollectionUtils.convertListToArray(listOfA, B.class)也不是为我工作,谁能告诉我我做错了什么?如果我创建了两个包装类,一个包含List,另一个包含b[],那么mapper.map函数就可以正常工作。如下所示:
public class C{
    private List<A> items = null;
    public List<A> getItems(){
      return this.items;
    }
    public void setItems(List<A> items){
      this.items = items;
    }
}
public class D{
    private B[] items = null;
    public B[] getItems(){
      return this.items;
    }
    public void setItems(B[] items){
      this.items = items;
    }
}这工作起来很奇怪。
List<A> listOfA = getListofAObjects();
C c = new C();
c.setItems(listOfA);
Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();
D d = mapper.map(c, D.class);
B[] bs = d.getItems();如何在不使用包装器类(C & D)的情况下做我想做的事情?一定有更简单的方法...谢谢!
发布于 2010-06-21 18:47:12
在开始迭代之前,您应该知道listOfA中有多少项。为什么不实例化新的BlistOfA.size(),然后遍历A,将新的B实例直接放入数组中。您将省去对listOfB中所有项的额外迭代,并且代码在引导时实际上将更易于阅读。
Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();
List<A> listOfA = getListofAObjects();
B[] arrayOfB = new B[listOfA.size()];
int i = 0;
for (A a : listOfA) {
    arrayOfB[i++] = mapper.map(a, B.class);
}发布于 2010-06-18 10:36:39
好吧,那我就是个笨蛋。我太习惯Dozer替我做所有的工作了..。我所需要做的就是迭代A的列表,创建B的列表,然后将该列表转换为B的数组。
Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();
List<A> listOfA = getListofAObjects();
Iterator<A> iter = listOfA.iterator();
List<B> listOfB = new ArrayList<B>();
while(iter.hasNext()){
   listOfB.add(mapper.map(iter.next(), B.class));
}
B[] bs = listOfB.toArray(new B[listOfB.size()]);问题解决了!
发布于 2011-05-06 19:27:37
如果我可以写下面的代码,它会更有意义,而且它可以工作
List<A> listOfA = getListofAObjects();
Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();
B[] bs = mapper.map(listOfA, B[].class);https://stackoverflow.com/questions/3066851
复制相似问题