I have read how to simply import a groovy file in another groovy script
I want to define common functions in one groovy file and call those functions from other groovy files.
I understand this would be using Groovy like a scripting language i.e, I dont need classes/objects. I am trying to something like dsl that can be done in groovy. All variables will be asserted from Java and I want to execute groovy script in a shell.
Is this possible at all ? Can someone provide some example.
For example, using "some/subpackage/Util. groovy" would result in searching at WORK_DIR/some/subpackage/Util. groovy . Follow the Java class naming convention to name your groovy scripts.
A simple import is an import statement where you fully define the class name along with the package. For example the import statement import groovy. xml. MarkupBuilder in the code below is a simple import which directly refers to a class inside a package.
evaluate(new File("../tools/Tools.groovy"))
Put that at the top of your script. That will bring in the contents of a groovy file (just replace the file name between the double quotes with your groovy script).
I do this with a class surprisingly called "Tools.groovy".
As of Groovy 2.2 it is possible to declare a base script class with the new @BaseScript
AST transform annotation.
Example:
file MainScript.groovy:
abstract class MainScript extends Script { def meaningOfLife = 42 }
file test.groovy:
import groovy.transform.BaseScript @BaseScript MainScript mainScript println "$meaningOfLife" //works as expected
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With