Reputation: 1048
Warning. This is a total newbie question for Groovy.. I'm from a Java background and I don't want to do it that way, unless I must.
I'd like to create either a mapping that will traverse one object graph easily between another object graph.
Like:
customer.contact.address.identifier = incomingContact.location.address.idCode
Both of the above object structures are completely different, with sometimes different data types. In the above snippet, identifier is a Long, and idCode is a String. Also, some of the objects are null, so I want to create sturctures on the fly.
How can this be done better with groovy's features of closures and more functional programming?
I was originally thinking inheritence or reflection solutions to minimize if/else conditions and instanceof based programming.
Any thoughts.
Here's some pseudo code that I started which already has smells of java:
Method call:
customer.contact.address.identifier = convert(incomingContact.location.address.idCode)
And here's the method:
Long convert(Object fromObject) {
//example usage that were prototyping for this method (generically)
//fromObject = Long.valueOf(5);
println "convert has: [" + fromObject + "]"
if(fromObject != null) {
return fromObject;
}
return null;
}
The above snippet has complexity and problems in itself. For one, it errors out when I want to set back the calling structure a null object, but a "Long".
The immediate error is:
groovy.lang.MissingMethodException: No signature of method: customer.contact.address.setIdentifier() is applicable for argument types: (null) values: [null]
My alternative thought is to use a mapping tool such as: http://dozer.sourceforge.net/ and allowing it to handle traversal of both graphs, but it's java again, which I wanted that groovy dynamic type solution.
Upvotes: 0
Views: 853
Reputation: 187499
If you simply want to bind properties from one object to another, Groovy's features won't help you much. Something like Dozer might be worth a look.
BTW, here's a Groovier way to write the code above:
Long convert(fromObject) {
println "convert has: [" + fromObject + "]"
fromObject as Long
}
Upvotes: 1