Grails Domain Objects
You can use Grails Gorm's getPersistentProperties()
, if you are not including any transient properties on your map.
def domainProperties = [:]
YourDomain.gormPersistentEntity.persistentProperties.each { prop ->
domainProperties.put(prop.name, yourDomainObject."$prop.name")
}
If you want to include transient properties, just write another loop on the property transients
:
YourDomain.transients.each { propName ->
domainProperties.put(propName, yourDomainObject."$propName")
}
Read my answer here for some more detail on persistentProperties
.
Groovy Objects
For simple POGOs, as others pointed out in their answers, the following does the job:
def excludes = ['class']
def domainProperties = yourPogo.properties.findAll { it.key !in excludes }
or
Map map = [:]
yourPogo.class.declaredFields.each {
if (!it.synthetic) map.put(it.name, yourPogo."$it.name")
}
You can get the best alternative that suits your needs and implement it on a method in a trait
to be inherited or create a utility method that accepts the object as argument.