我试图在 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 实例查找类,它会起作用,但我想避免这种情况。