问题描述
我想允许用户遍历域类并打印出转储的东西.我的第一个问题:假设以下工作正常:
I want to allow users to traverse the domain classes and print out dumps of stuff. My frist problem: assuming the following works just fine:
//this works
class EasyStuffController{
def quickStuff = {
def findAThing = MyDomainClass.findByStuff(params.stuff)
[foundThing:findAThing]
}
}
写下我想说的内容的正确方法是什么:
What is the proper way to write what I am trying to say below:
//this doesn't
class EasyStuffController{ servletContext ->
def quickStuff = {
def classNameString = "MyDomainClass" //or params.whichOne something like that
def domainHandle = grailsApplication.domainClasses.findByFullName(classNameString)
//no such property findByFullName
def findAThing = domainHandle.findByStuff(params.stuff)
[foundThing:findAThing]
}
}
//this also doesn't
class EasyStuffController{ servletContext ->
def quickStuff = {
def classNameString = "MyDomainClass" //or params.whichOne something like that
def domainHandle
grailsApplication.domainClasses.each{
if(it.fullName==classNameString)domainHandle=it
}
def findAThing = domainHandle.findByStuff(params.stuff)
//No signature of method: org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass.list() is applicable
[foundThing:findAThing]
}
}
上面的那些行根本不起作用.我试图让用户能够选择任何域类并用东西"取回东西.假设:所有领域类都有一个相同类型的 Stuff 字段.
Those lines above don't work at all. I am trying to give users the ability to choose any domain class and get back the thing with "stuff." Assumption: all domain classes have a Stuff field of the same type.
推荐答案
如果你知道完整的包,你可以使用这个:
If you know the full package, you can use this:
String className = "com.foo.bar.MyDomainClass"
Class clazz = grailsApplication.getDomainClass(className).clazz
def findAThing = clazz.findByStuff(params.stuff)
如果您不使用包,这也将起作用.
That will also work if you don't use packages.
如果您使用包,但用户将只提供没有包的类名,并且名称在所有包中都是唯一的,那么您可以使用:
If you use packages but users will only be providing the class name without the package, and names are unique across all packages, then you can use this:
String className = "MyDomainClass"
Class clazz = grailsApplication.domainClasses.find { it.clazz.simpleName == className }.clazz
def findAThing = clazz.findByStuff(params.stuff)
这篇关于Grails:按名称查找域类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!