How do you call a function defined in a Groovy script file from Java?
Example groovy script:
def hello_world() {
println "Hello, world!"
}
I've looked at the GroovyShell, GroovyClassLoader, and GroovyScriptEngine.
How do you call a function defined in a Groovy script file from Java?
Example groovy script:
def hello_world() {
println "Hello, world!"
}
I've looked at the GroovyShell, GroovyClassLoader, and GroovyScriptEngine.
Either
One advantage of the spring approach is the concept of 'refreshable beans'. That is, Spring can be configured to monitor your script file for modifications, and replace at runtime.
The simplest way is to compile the script into a java class file and just call it directly. Example:
Just more elegant ways:
And if script class extends
groovy.lang.Script
:No need to extend
groovy.lang.Script
if you just want callmain
method of your groovy class:One simple example:
Testing
Assuming you have a file called
test.groovy
, which contains (as in your example):Then you can create a file
Runner.java
like this:compile it with:
(Note: The warnings are left as an exercise to the reader) ;-)
Then, you can run this Runner.class with:
You too can use the Bean Scripting Framework to embed any scripting language into your Java code. BSF give you the opportunity of integrate other languages, but is not native integration.
If you are clearly focused to use Groovy the GroovyScriptEngine is the most complete solution.
=)