Robo
Robo

Reputation: 271

About Adding import package in Groovy by customizing compilation process

I am writing a java file in which i am parsing the given groovy file using GroovyClassLoader to find the class in it. To do this, i have to import some class (like org.junit.Test) and add package and add static import also. Since i am using old groovy version 1.6, i can not use compilation customizers as these classes not available in this version. So to import custom classes, i had to write custom groovy class loader by extending groovy class loader class like below,

...

public static class DefaultImportClassLoader extends GroovyClassLoader {
public DefaultImportClassLoader(ClassLoader cl){
    super(cl);
}

public CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource codeSource) {
         CompilationUnit cu = super.createCompilationUnit(config, codeSource);
         cu.addPhaseOperation(new SourceUnitOperation() {
         public void call(SourceUnit source) throws CompilationFailedException {
             //source.getAST().addImport("Test",ClassHelper.make("org.junit.Test")); //working
        source.getAST().addImportPackage("org.junit.");
        }}, Phases.CONVERSION);

        return cu;
    }

}

here add import package is not working. Would any one give right suggestion way of using addImportPackage().

Upvotes: 2

Views: 803

Answers (1)

fonkap
fonkap

Reputation: 2509

I've tested your code and works perfectly for me. (with groovy-all-1.6.9.jar) (edit: groovy-all-1.6.0.jar works fine too)
How do you use your class DefaultImportClassLoader?
I've done:

    public static void main(String[] args) throws InstantiationException, IllegalAccessException{
        GroovyClassLoader loader = new DefaultImportClassLoader(new GroovyClassLoader());
        Class groovyClass = loader.parseClass(DefaultImportClassLoader.class.getClassLoader().getResourceAsStream("so_22729226/test.groovy"));
        GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
        groovyObject.invokeMethod("run", null);
    }

With this Groovy class:

class so_22729226_Test {
    def run(){
        print Test.class
    }
}

And I get the expected output: interface org.junit.Test

If I use the standard loader I get:

 Caused by: groovy.lang.MissingPropertyException: No such property: Test for class: so_22729226_Test

Which is the expected behaviour too.

Upvotes: 2

Related Questions