Grails: find domain class by name

a 夏天 提交于 2019-11-26 20:13:13

问题


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]
  }
}

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.


回答1:


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)


来源:https://stackoverflow.com/questions/6338148/grails-find-domain-class-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!