Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Grails domain class from GroovyShell script

Tags:

grails

groovy

I'm trying to use GroovyShell to evaluate some snippets of code from within a Grails application, but I don't seem to be able to access our Grails domain classes. For example when I try to evaluate something like this:

Eval.me("my.package.MyDomainClass.get(1)")

I see an error like this:

groovy.lang.MissingPropertyException: No such property: my for class: Script1

Any thoughts on how I can get this to work?

Thanks.

like image 887
Martin Dow Avatar asked Mar 06 '26 04:03

Martin Dow


1 Answers

I figured out how to get this working. By default a GroovyShell instance clearly evaluates the script in its own classloader, so none of your Grails artefacts are available. There's an alternative constructor where you can pass in another classloader, so this does what I need within the context of a Grails application (when running inside a grails console, for example):

def shell = new GroovyShell(this.class.classLoader)
shell.evaluate("my.package.MyDomainClass.get(1)")
like image 54
Martin Dow Avatar answered Mar 08 '26 20:03

Martin Dow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!