Last active
August 7, 2020 23:47
-
-
Save dkordik/6d5751ca34a9edfcaaf928ce5ae05c5d to your computer and use it in GitHub Desktop.
Groovy- merging an object with another existing object without explicitly mapping properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BulkResponse { | |
String subject; | |
} | |
bulkResponse = new BulkResponse(subject:'Hi Rohit!') | |
//-- | |
class ThreadResponse extends BulkResponse { | |
String campaignName; | |
} | |
// -- approach 1 | |
threadResponse = new ThreadResponse(campaignName: 'My Campaign') | |
bulkResponse.properties.each { | |
threadResponse.metaClass[it.key] = it.value | |
} | |
println threadResponse.getCampaignName() //My Campaign | |
println threadResponse.getSubject() //Hi Rohit! | |
//-- approach 2 | |
private def getObjectProperties(Object object) { | |
object.properties.findAll { k, v -> k != 'class' } | |
} | |
ThreadResponse threadResponse2 = getObjectProperties(bulkResponse) | |
threadResponse2.setCampaignName('My Campaign 2') | |
println threadResponse2.getCampaignName() //My Campaign 2 | |
println threadResponse2.getSubject() //Hi Rohit! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment