6

I would like to get the field names of a class and maybe store it in a list. Can anyone help? Thanks.

noob
  • 300
  • 5
  • 16

4 Answers4

7

You can try this to get field names of domain class.

YourClass.declaredFields.each {
  if (!it.synthetic) {
    println it.name
  }
}
Meam
  • 257
  • 3
  • 12
Ramesh
  • 416
  • 3
  • 10
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.

http://groovy.codehaus.org/JN3535-Reflection