Reputation: 300
I would like to get the field names of a class and maybe store it in a list. Can anyone help? Thanks.
Upvotes: 6
Views: 7970
Reputation: 1195
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'...]
Upvotes: 7
Reputation: 416
You can try this to get field names of domain class.
YourClass.declaredFields.each {
if (!it.synthetic) {
println it.name
}
}
Upvotes: 7
Reputation: 300
Just found it out, this one works:
def names = grailsApplication.getDomainClass('com.foo.Person').persistentProperties.collect { it.name }
Upvotes: 4
Reputation: 1
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
Upvotes: 0