如果Grails中包含一个带有GORM的查询,如何将字符串转换为一段代码?

如果Grails中包含一个带有GORM的查询,如何将字符串转换为一段代码?,grails,reflection,groovy,Grails,Reflection,Groovy,下一段Groovy代码在Grails中工作(谢谢): 不幸的是,如果我们引入Grails的神奇查询,它将失败: String string2code = "return DomainClassExample.findByName('hello')"; // String string2code = "DomainClassExample.where { name == 'hello' }" def queryResult = new GroovyShell().evaluate string2c

下一段Groovy代码在Grails中工作(谢谢):

不幸的是,如果我们引入Grails的神奇查询,它将失败:

String string2code = "return DomainClassExample.findByName('hello')";
// String string2code = "DomainClassExample.where { name == 'hello' }"
def queryResult = new GroovyShell().evaluate string2code
这就是错误:

Class
    groovy.lang.MissingPropertyException
Message
    No such property: DomainClassExample for class: Script1

可能吗?如何操作?

GroovyShell使用的类加载器不知道运行时加载的Grails工件类。但是如果您将Grails类加载器作为其父类加载器传入,那么这些类将解析。Grails将其类加载器注册为线程的上下文类加载器,因此这是一种快速实现所需功能的方法:

def queryResult = new GroovyShell(Thread.currentThread().contextClassLoader).evaluate string2code

由此推论,您最初尝试的将在部署的WAR或
grails run WAR
(其中工件与Groovy运行时本身在同一个类加载器中)中工作,但在
run app
中不起作用。谢谢!我不明白你说的“跑步应用”是什么意思。我认为运行应用程序的唯一方法是编写“grails run app”(在Eclipse run As-grails应用程序中,我认为它与“grails run app”相同)
def queryResult = new GroovyShell(Thread.currentThread().contextClassLoader).evaluate string2code