1

The next piece of Groovy code works in Grails (thanks @Will P) for your answer:

String string2code = "variable = 'hello'; return variable.toUpperCase()";

def result = new GroovyShell().evaluate string2code
assert result == "HELLO"

Unfortunately, if we introduce the magic querying of Grails, it fails:

String string2code = "return DomainClassExample.findByName('hello')";
// String string2code = "DomainClassExample.where { name == 'hello' }"
def queryResult = new GroovyShell().evaluate string2code

This is the error:

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

Is it possible? How?

4

1 回答 1

2

使用的类加载器GroovyShell不知道在运行时加载的 Grails 工件类。但是,如果您将 Grails 类加载器作为其父类加载器传入,则这些类将解析。Grails 将其类加载器注册为线程的上下文类加载器,因此这是一种快速的方式来做你想做的事:

def queryResult = new GroovyShell(Thread.currentThread().contextClassLoader).evaluate string2code
于 2013-07-05T15:02:55.437 回答