anish
anish

Reputation: 7412

Default imports groovy

groovy defualt imports

Is it possible to have our own package in default imports? Is there any way to tell the groovy runtime to use my own package as default import?

Upvotes: 5

Views: 1053

Answers (2)

Hugues M.
Hugues M.

Reputation: 20467

Since Groovy 1.8 there is an easier way with ImportCustomizer:

def importCustomizer = new ImportCustomizer()
importCustomizer.addImports('com.looneytunes.Coyote', 'com.looneytunes.RoadRunner')
importCustomizer.addStarImports('com.acme')
importCustomizer.addStaticStars('com.looneytunes.Physics')
def configuration = new CompilerConfiguration()
configuration.addCompilationCustomizers(importCustomizer)
def shell = new GroovyShell(configuration)
shell.evaluate """
    new Coyote().startPlanToCatch(new RoadRunner())  // no need for explicit imports
        .useContraption(new PortableHole())          // from com.acme
        .withPhysicsViolation({ forgetGravity(it) }) // method from com.looneytunes.Physics
        .start()
"""

Upvotes: 2

gotomanners
gotomanners

Reputation: 7906

This JIRA covers you question.

The bulk of it is here.

 class DefaultImportSourceUnitOperation extends SourceUnitOperation {
     public void call(SourceUnit source) throws CompilationFailedException {
         source.getAST().addImportPackage("pkg1.pgk2.pkg3.");
     } 
}

 class DefaultImportClassLoader extends GroovyClassLoader {
     protected CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource
 codeSource) {
         CompilationUnit cu = super.createCompilationUnit(config, codeSource)

         cu.addPhaseOperation(new DefaultImportSourceUnitOperation(), Phases.CONVERSION)

         return cu
     }
}

Be sure not to forget to add the . to the end of the package declaration.

Goodluck!

Upvotes: 4

Related Questions