spock99
spock99

Reputation: 1184

how to get grails class name from a string

Here is a stripped down version of my grails domain objects:

//this is a lookup table
class PetType {
  String description
}

class Family {
   static hasMany = [
      petTypePreferred:PetType
   ]
}

In my controller I'm getting returned back from my gsp a parameter string value of 'petTypePreferred'. Knowing that string value, and knowing the Domain class Family, how can I determine the Domain class from the 'petTypePreferred' string value? In grails 2.2.4 the getPropertyByName(String value) method isn't seen as valid on a domain object, even though it's in the javadoc.

So I have String petTypePreferred, and Class Family, but I need to find Class PetType given those 2 pieces of information.

Upvotes: 0

Views: 522

Answers (1)

micha
micha

Reputation: 49552

I am not sure what exactly you want:

Getting the domain class name:

hasMany is a simple static Map in Family. The Map stores the field name as key and the target type as value. So you can get the domain class PetType from the string petTypePreferred using:

Familiy.hasMany['petTypePreferred']

Getting the value of description inside PetType for a given Family instance:

A Family can have multiple pet types (hasMany), so the result has to be a collection:

Family family = ...
List descriptions = family['petTypePreferred']*.description

This gives you the list of PetType descriptions for a Family instance named family.

Upvotes: 1

Related Questions