I would like to get the field names of a class and maybe store it in a list. Can anyone help? Thanks.
Asked
Active
Viewed 7,786 times
4 Answers
7
You can use gormPersistentEntity
for any domain object, this works with Grails 2.4.4 at least:
def names = Person.gormPersistentEntity.persistentPropertyNames
//returns ['firstName', 'lastName'...]
you can also get natural name using GrailsNameUtils
like so:
def naturalNames = Person.gormPersistentEntity.persistentPropertyNames.collect {
grails.util.GrailsNameUtils.getNaturalName(it)
}
//returns ['First Name', 'Last Name'...]
def capitilizedNames = Person.gormPersistentEntity.persistentProperties.collect{
it.capitilizedName
}
//returns ['FirstName', 'LastName'...]

Ibrahim.H
- 1,062
- 1
- 13
- 22
4
Just found it out, this one works:
def names = grailsApplication.getDomainClass('com.foo.Person').persistentProperties.collect { it.name }

noob
- 300
- 5
- 16
0
You can iterate over the fields of a class like this.
YourClass.fields.each { println it.name }
If you need to put them into a list you could use collect() or populate it within the each.