14

我试图在 Grails 中动态创建域对象,但遇到了一个问题,即对于引用另一个域对象的任何属性,元属性告诉我它的类型是“java.lang.Object”而不是预期的类型。

例如:

class PhysicalSiteAssessment {
    // site info
    Site site
    Date sampleDate
    Boolean rainLastWeek
    String additionalNotes
    ...

是域类的开始,它引用另一个域类“站点”。

如果我尝试使用此代码(在服务中)动态查找此类的属性类型:

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}'"
}

那么结果是它识别 Java 类,但不识别 Grails 域类。输出包含以下几行:

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' 

问题是我想使用动态查找来查找匹配的对象,例如做一个

def targetObjects = propertyClass."findBy${idName}"(idValue)

其中 propertyClass 是通过自省检索的,idName 是要查找的属性的名称(不一定是数据库 ID),idValue 是要查找的值。

这一切都结束于:

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]

有没有办法找到该属性的实际域类?或者,对于查找未给出类型的域类的实例(只有具有该类型的属性名称)的问题,可能还有其他解决方案?

如果我使用类型名称是属性名称大写(“site”->“Site”)的约定来通过 grailsApplication 实例查找类,它会起作用,但我想避免这种情况。

4

4 回答 4

16

Grails 允许您通过 GrailsApplication 实例访问域模型的一些元信息。你可以这样查找:

import org.codehaus.groovy.grails.commons.ApplicationHolder
import org.codehaus.groovy.grails.commons.DomainClassArtefactHandler

def grailsApplication = ApplicationHolder.application
def domainDescriptor = grailsApplication.getArtefact(DomainClassArtefactHandler.TYPE, "PhysicalSiteAssessment")

def property = domainDescriptor.getPropertyByName("site")
def type = property.getType()
assert type instanceof Class

接口:

于 2009-06-10T07:57:03.913 回答
15

您可以使用GrailsClassUtils.getPropertyType(clazz, propertyName)

于 2011-05-25T06:37:56.793 回答
3

Siegfried 提供的上述答案在 Grails 2.4 附近的某个地方已经过时。ApplicationHolder 已过时。

现在,您可以从每个域类拥有的domainClass属性中获取真实的类型名称。

entityClass.domainClass.getProperties().each() {
    println "Property '${it.name}' is of type '${it.type}'"
}
于 2015-07-14T19:26:29.340 回答
0

注意:这个答案不是直接与问题相关,而是与 IMO 相关。

当我试图解决集合关联的“通用类型”时,我正用头撞墙、地面和周围的树木:

class A {
    static hasMany = {
        bees: B
    }

    List bees
}

结果发现,最简单但最合理的方式只是(我没有尝试,但在 3 小时后):

A.getHasMany()['bees']
于 2012-02-17T14:13:53.123 回答