The usual method of running a non-gui Groovy script is with the groovy JVM runner. This is done using a script file such as groovy.bat in Windows. Another option is to use the Groovy interactive Console which is a Gui for editing and running Groovy scripts.
Sample groovy script
println 'Hello world!'
Run via the command line invocation or double click on file explorer:
C:\temp>groovy Hello.groovy Hello world!
Run using the Groovy console:
C:\temp>groovyconsole Hello.groovy
This results in the Console as shown below after the script is then executed withing the console.
It is also possible to programmatically execute the script in the Groovy Console directly by using the Console class.
import groovy.transform.TypeChecked import groovy.ui.Console @TypeChecked class ConsoleRunner { /** * Do the 'Hello world!' as an example. */ static void main(args) { Console console = new Console(); console.run(); def script = "println 'Hello world!'" File file = File.createTempFile("hello",null) file.deleteOnExit() file.setText(script) console.loadScriptFile(file) console.runScript(); } }
How this works
Here I sneak in the script text using a temporary file; did not find a direct way of doing it. Then I invoke the loaded script. This results in the same Groovy Console image as shown above.
Of course, if you already have a Groovy script stored in a file, it is even easier, skip the temp file creation.
Alternatives?
I’m sure there is some way to bootstrap a Groovy script to use the Console for its runtime or a way of subclassing or extending the Console itself to serve as a generic runner.
Applications?
Does this have any practical use? Maybe.
Further Reading