Question

Extended GroovyClassloader and override loadclass method

If I make lookupScriptFiles "true" in the loadClass() method the script run and doesn't require an import statement referencing a groovy class in a different package

i have extended GroovyClassloader, and override the loadclass method, in the loadclass the argument lookupScriptFiles =true

When this is true, it sucessfully compiles even first.groovy don't have import statement

when lookupScriptFiles=false it throws compilation error as expected.

my source code snippet

    C:\>cat first.groovy
def cos=new Second()
==============================================================
C:>cat Second.groovy
package com.test
class Second
{
Second()
{
        println "Anish"
}

}
=========================================================

C:\bin>echo %CLASSPATH%
C:\zGroovy\bin;C:\vsexclude\opt\groovy-1.7.2\embeddable\groovy-all-1.7.2.jar
===============================================
C:\vsexclude\trees\bac-4.2\workspace\zGroovy\bin>java GCtest
path------>>C:\first.groovy
Anish
=================================

import groovy.lang.GroovyClassLoader;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilerConfiguration;
/**
 * @author Anish
 */
public class GCloader extends GroovyClassLoader {
    public GCloader(ClassLoader parent) {
        super(parent, new CompilerConfiguration());
    }
    @Override
    public Class<?> loadClass(final String name, boolean lookupScriptFiles,
            boolean preferClassOverScript, boolean resolve)
            throws ClassNotFoundException, CompilationFailedException {
        //return loadFiles(name, true, preferClassOverScript, resolve);
        return super.loadClass(name, true,
                preferClassOverScript, resolve);
    }
}

No correct solution

OTHER TIPS

Assuming your question is:

If I set lookupScriptFiles to true, can I remove the import statements from my groovy scripts?

Then the answer is no. The classloader will try to lookup scripts it doesn't know about, but you will still need to imports to tell it in which packages to look for each class


Update

So, you have two groovy files in the same directory, one of which you have arbitrarily added a package statement to.

I assume you are loading the classes straight from scripts (yet another thing you don't say in your question)

If this is the case, then you will need to tell the classloader to lookup the other scripts to compile to classes.

If you don't -- as you have seen -- it will not work (imports or no imports)

However, putting two groovy files in the same folder, and just adding a package line to one of them is awful coding practice, and I'm surprised you got anything working

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top