views:

1631

answers:

2

I'd like to do something like:

ArrayList<CustomObject> objects = new ArrayList<CustomObject>();
...
DozerBeanMapper MAPPER = new DozerBeanMapper();
...
ArrayList<NewObject> newObjects = MAPPER.map(objects, ...);

Assuming:

<mapping>
  <class-a>com.me.CustomObject</class-a>
  <class-b>com.me.NewObject</class-b>   
    <field>  
      <a>id</a>  
      <b>id2</b>  
    </field>  
</mapping>

I tried :

ArrayList<NewObject> holder = new ArrayList<NewObject>();
MAPPER.map(objects, holder);

but the holder object is empty. I also played with changing the second argument without any luck...

+1  A: 

What is happening is that you are getting bitten by type erasure. At runtime, java only sees an ArrayList.class. The type of CustomObject and NewObject aren't there, so Dozer is attempting to map a java.util.ArrayList, not your CustomObject to NewObject.

What should work (totally untested):

List<CustomObject> ori = new ArrayList<CustomObject>();
List<NewObject> n = new ArrayList<NewObject>();
for (CustomObject co : ori) {
   n.add(MAPPER.map(co, CustomObject.class));
}
Yishai
So how would you do it other than having a loop mapping each object one by one?
Stephane Grenier
There is no way other than a loop, that I can see (unless Dozer supports operations on collections, I'm not really familiar with its API).
Yishai
That's the question. I believe it's suppose to support a way without looping. I just can't find the specific details.
Stephane Grenier
+3  A: 

To quote:

"Nested collections are handled automatically, but you are correct that top level collections need to be iterated over. Currently there isn't a more elegant way to handle this."

Someone has figured a way to do it without a looping construct in your code base, but I think it's just easier (and more readable/maintainable) to put it in your code. Hopefully they'll add this ability sooner than later.

Stephane Grenier