Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I get the type (class) of a property of a Grails domain object?
    text
    copied!<p>I'm trying to dynamically create domain objects in Grails and encountered the problem that for any property referencing another domain object the metaproperty tells me its type is "java.lang.Object" and not the expected type.</p> <p>For example:</p> <pre><code>class PhysicalSiteAssessment { // site info Site site Date sampleDate Boolean rainLastWeek String additionalNotes ... </code></pre> <p>is the beginning of a domain class, which references another domain class "Site". </p> <p>If I try to dynamically find the property types for this class by using this code (in a service):</p> <pre><code>String entityName = "PhysicalSiteAssessment" Class entityClass try { entityClass = grailsApplication.getClassForName(entityName) } catch (Exception e) { throw new RuntimeException("Failed to load class with name '${entityName}'", e) } entityClass.metaClass.getProperties().each() { println "Property '${it.name}' is of type '${it.type}'" } </code></pre> <p>then the result is that it recognizes the Java classes, but not the Grails domain class. The output contains the following lines:</p> <pre><code>Property 'site' is of type 'class java.lang.Object' Property 'siteId' is of type 'class java.lang.Object' Property 'sampleDate' is of type 'class java.util.Date' Property 'rainLastWeek' is of type 'class java.lang.Boolean' Property 'additionalNotes' is of type 'class java.lang.String' </code></pre> <p>The problem is that I would like to use the dynamic lookup to find matching objects, e.g. do a</p> <pre><code>def targetObjects = propertyClass."findBy${idName}"(idValue) </code></pre> <p>where the propertyClass is retrieved via introspection, idName is the name of the property to look up (not necessarily the database ID) and idValue is the value to find.</p> <p>It all ends in:</p> <pre><code>org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingMethodException: No signature of method: static java.lang.Object.findByCode() is applicable for argument types: (java.lang.String) values: [T04] </code></pre> <p>Is there a way to find the actual domain class for the property? Or maybe some other solution to the problem of finding an instance of a domain class whose type is not given (only a property name that has the type)?</p> <p>It works if I use the convention that the type name is the property name capitalized ("site"->"Site") to look up the class via the grailsApplication instance, but I would like to avoid that.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload