Пример #1
0
  /**
   * Compile the specified Groovy source files, applying any {@link CompilerAutoConfiguration}s. All
   * classes defined in the files will be returned from this method.
   *
   * @param file the file to compile
   * @return compiled classes
   * @throws CompilationFailedException
   * @throws IOException
   */
  public Class<?>[] compile(File... file) throws CompilationFailedException, IOException {

    this.loader.clearCache();
    List<Class<?>> classes = new ArrayList<Class<?>>();

    CompilerConfiguration configuration = this.loader.getConfiguration();

    CompilationUnit compilationUnit = new CompilationUnit(configuration, null, this.loader);
    SourceUnit sourceUnit =
        new SourceUnit(file[0], configuration, this.loader, compilationUnit.getErrorCollector());
    ClassCollector collector = this.loader.createCollector(compilationUnit, sourceUnit);
    compilationUnit.setClassgenCallback(collector);

    compilationUnit.addSources(file);

    addAstTransformations(compilationUnit);

    compilationUnit.compile(Phases.CLASS_GENERATION);
    for (Object loadedClass : collector.getLoadedClasses()) {
      classes.add((Class<?>) loadedClass);
    }
    ClassNode mainClassNode = (ClassNode) compilationUnit.getAST().getClasses().get(0);
    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()]);
  }
Пример #2
0
    protected Class createClass(byte[] code, ClassNode classNode) {
      BytecodeProcessor bytecodePostprocessor = unit.getConfiguration().getBytecodePostprocessor();
      byte[] fcode = code;
      if (bytecodePostprocessor != null) {
        fcode = bytecodePostprocessor.processBytecode(classNode.getName(), fcode);
      }
      GroovyClassLoader cl = getDefiningClassLoader();
      Class theClass =
          cl.defineClass(
              classNode.getName(), fcode, 0, fcode.length, unit.getAST().getCodeSource());
      this.loadedClasses.add(theClass);

      if (generatedClass == null) {
        ModuleNode mn = classNode.getModule();
        SourceUnit msu = null;
        if (mn != null) msu = mn.getContext();
        ClassNode main = null;
        if (mn != null) main = (ClassNode) mn.getClasses().get(0);
        if (msu == su && main == classNode) generatedClass = theClass;
      }

      return theClass;
    }