Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get domain class field names

Tags:

grails

groovy

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

like image 697
noob Avatar asked Feb 27 '13 02:02

noob


3 Answers

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

YourClass.declaredFields.each {
  if (!it.synthetic) {
    println it.name
  }
}
like image 179
Ramesh Avatar answered Oct 19 '22 00:10

Ramesh


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'...]
like image 7
Ibrahim.H Avatar answered Oct 18 '22 23:10

Ibrahim.H


Just found it out, this one works:

def names = grailsApplication.getDomainClass('com.foo.Person').persistentProperties.collect { it.name }
like image 4
noob Avatar answered Oct 19 '22 00:10

noob