Adding transparent imports to a script
In this recipe, we will learn how to transparently add one or more import statements to a Groovy script.
Why is this feature significant? For a start, it reduces the amount of code required to use a library. But above all, it may be the first step in building your own DSL as it helps to remove friction. This is because your DSL users don't have to write any import statements. The ImportCustomizer
class allows the following import variants:
Class imports, optionally aliased
Star imports
Static imports, optionally aliased
Static star imports
Getting ready
For the sake of demonstration, we will create a script that requires some classes from the amazing Google Guava library. Additionally, we will also need to statically import a groovy.json.JsonOutput
utility class, which is indisputably a very fine collection of the utility methods for JSON printing. A script that wishes to use the classes mentioned previously would start with the following import statements...