Search in sources :

Example 1 with ClassCollector

use of groovy.lang.GroovyClassLoader.ClassCollector in project spring-boot by spring-projects.

the class GroovyCompiler method compile.

/**
	 * Compile the specified Groovy sources, applying any
	 * {@link CompilerAutoConfiguration}s. All classes defined in the sources will be
	 * returned from this method.
	 * @param sources the sources to compile
	 * @return compiled classes
	 * @throws CompilationFailedException in case of compilation failures
	 * @throws IOException in case of I/O errors
	 * @throws CompilationFailedException in case of compilation errors
	 */
public Class<?>[] compile(String... sources) throws CompilationFailedException, IOException {
    this.loader.clearCache();
    List<Class<?>> classes = new ArrayList<>();
    CompilerConfiguration configuration = this.loader.getConfiguration();
    CompilationUnit compilationUnit = new CompilationUnit(configuration, null, this.loader);
    ClassCollector collector = this.loader.createCollector(compilationUnit, null);
    compilationUnit.setClassgenCallback(collector);
    for (String source : sources) {
        List<String> paths = ResourceUtils.getUrls(source, this.loader);
        for (String path : paths) {
            compilationUnit.addSource(new URL(path));
        }
    }
    addAstTransformations(compilationUnit);
    compilationUnit.compile(Phases.CLASS_GENERATION);
    for (Object loadedClass : collector.getLoadedClasses()) {
        classes.add((Class<?>) loadedClass);
    }
    ClassNode mainClassNode = MainClass.get(compilationUnit);
    Class<?> mainClass = null;
    for (Class<?> loadedClass : classes) {
        if (mainClassNode.getName().equals(loadedClass.getName())) {
            mainClass = loadedClass;
        }
    }
    if (mainClass != null) {
        classes.remove(mainClass);
        classes.add(0, mainClass);
    }
    return classes.toArray(new Class<?>[classes.size()]);
}
Also used : CompilationUnit(org.codehaus.groovy.control.CompilationUnit) ClassNode(org.codehaus.groovy.ast.ClassNode) ClassCollector(groovy.lang.GroovyClassLoader.ClassCollector) ArrayList(java.util.ArrayList) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) URL(java.net.URL)

Aggregations

ClassCollector (groovy.lang.GroovyClassLoader.ClassCollector)1 URL (java.net.URL)1 ArrayList (java.util.ArrayList)1 ClassNode (org.codehaus.groovy.ast.ClassNode)1 CompilationUnit (org.codehaus.groovy.control.CompilationUnit)1 CompilerConfiguration (org.codehaus.groovy.control.CompilerConfiguration)1