加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何获取Grails域对象的属性的类型(class)?

发布时间:2020-12-14 16:35:30 所属栏目:大数据 来源:网络整理
导读:我正在尝试在Grails中动态创建域对象,并遇到问题:对于引用另一个域对象的任何属性,metaproperty告诉我,它的类型是“ java.lang.Object”,而不是预期的类型. 例如: class PhysicalSiteAssessment { // site info Site site Date sampleDate Boolean rainLas
我正在尝试在Grails中动态创建域对象,并遇到问题:对于引用另一个域对象的任何属性,metaproperty告诉我,它的类型是“ 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实例查找类,但是我想避免这种情况.

解决方法

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

API:

> GrailsApplication
> GrailsDomainClass
> GrailsDomainClassProperty

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读