Groovy-如何动态使用域类和静态函数

Groovy-如何动态使用域类和静态函数,groovy,gorm,Groovy,Gorm,我有一个域对象列表,每个域对象都需要调用,如下所示: (<DOMAIN CLASS>.withCriteria { dataSecurityGroups { 'in' 'id', entitiesIds as Long[] } }) 这个想法是让这个代码只运行一次,同时将代码更改为一个给定的参数。 我知道有几种方法可以使用g

我有一个域对象列表,每个域对象都需要调用,如下所示:

(<DOMAIN CLASS>.withCriteria {
                    dataSecurityGroups {
                        'in' 'id', entitiesIds as Long[]
                    }
                })
这个想法是让这个代码只运行一次,同时将代码更改为一个给定的参数。 我知道有几种方法可以使用groovy来实现它,我试着全部使用它们。 我需要知道做这件事的最佳做法和捷径


谢谢

我假设您使用的是Grails,因为您用Gorm标记了这个问题。如果是,请尝试以下方法:

Class clazz = grailsApplication.domainClasses.find { it.clazz.simpleName == "<DOMAINCLASS>" }.clazz
clazz.withCriteria {
    dataSecurityGroups {
        'in' 'id', entitiesIds as Long[]
    }
}

或者替换grailsApplication.domainClasses并使用您的域类列表。

您说过您有一个域类列表,因此下面的代码假设这是真的。你没有说你想对每个查询的结果做什么,所以我假设你已经控制住了

你可以这样做

def listOfDomainClasses = // you have initialized this list somehow...

listOfDomainClasses.each { domainClass ->
    def resultForThisClass = domainClass.withCriteria {
        dataSecurityGroups {
            'in' 'id', entitiesIds as Long[]
        }
    })

    // do something with resultForThisClass
}
/**
 * @param someDomainClass A domain class
 * @return the results of the query
 */
def myQueryMethod(Class someDomainClass) {
    someDomainClass.withCriteria {
        dataSecurityGroups {
            'in' 'id', entitiesIds as Long[]
        }
    }
}

我希望这会有所帮助。

不清楚您真正想要做的是什么,但也许您想要的是编写一个这样的方法

def listOfDomainClasses = // you have initialized this list somehow...

listOfDomainClasses.each { domainClass ->
    def resultForThisClass = domainClass.withCriteria {
        dataSecurityGroups {
            'in' 'id', entitiesIds as Long[]
        }
    })

    // do something with resultForThisClass
}
/**
 * @param someDomainClass A domain class
 * @return the results of the query
 */
def myQueryMethod(Class someDomainClass) {
    someDomainClass.withCriteria {
        dataSecurityGroups {
            'in' 'id', entitiesIds as Long[]
        }
    }
}
然后,您可以调用该方法并将任何合适的域类作为参数传递


这就是您要找的类型吗?

我的意思是,我几乎没有域类,而不是保存在内存中的列表。每次我需要使用其他代码时,我都在寻找替换开关盒块的代码。每次我需要使用其他代码时,我都在寻找替换开关盒块的代码。。我不明白那句话。