You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@groovy.apache.org by Rodolphe <rd...@gmail.com> on 2017/03/30 14:43:39 UTC

Dynamic class loader and dependency management

Hi all,

I have a web server application inside which I can launch groovy scripts
that can be modified/relaunched at any time, without needing to restart the
server. The groovy files have got some dependencies between them. As I
haven't found a way to perform the compilation of the script to be launched
with its dependencies, the solution I have found is the following: each
time I launch a script, I recompile all the groovy files inside a double
loop like this:

public Class<?>[] loadClasses() {
List<File> filesToLoad = new ArrayList<File>();
//...
parseLoop(filesToLoad);
//...
return classes.toArray(new Class[classes.size()]);
}

private void parseLoop(List<File> filesToLoad) { boolean changes = true;
int passCount = 1; while (changes) { int filesToLoadSize =
filesToLoad.size(); filesToLoad = parseClasses(passCount++, filesToLoad);
if ((filesToLoad.size()==0) || (filesToLoad.size() == filesToLoadSize)) {
changes = false; } } }

private List<File> parseClasses(int countPass, List<File> filesToLoad) {
System.out.println("## Pass "+ countPass);
List<File> errorFiles = new ArrayList<File>();
        for(Iterator<File> it = filesToLoad.iterator(); it.hasNext(); ) {
            File f = it.next();
            System.out.println("Loading = "+f.getPath());
            try {
                gcl.parseClass(f);
            }
            catch(IOException ioex) {
                System.err.print("Cannot load script " +
f.getAbsolutePath() + " Cause:" + ioex.getMessage());
            }
            catch (Exception e)
            {
             System.out.println("## error loading file " + f);
                System.err.print("Cannot load file " + f.getAbsolutePath()
+ " Cause:" + e.getMessage());
             errorFiles.add(f);
            }
        }
        return errorFiles;
}

I make several "passes" compiling all the files until I have solved all the
depency errors (same nb of errors between 2 passes.

It works fine, but I would expect groovy class loader to provide a way to
compile one file with its dependencies.
Does anyone know if there is a way to do that ?

Thank you in advance