Ejemplo n.º 1
0
 /**
  * Parses the given code source into a Java class. If there is a class file for the given code
  * source, then no parsing is done, instead the cached class is returned.
  *
  * @param shouldCacheSource if true then the generated class will be stored in the source cache
  * @return the main class defined in the given script
  */
 public Class parseClass(GroovyCodeSource codeSource, boolean shouldCacheSource)
     throws CompilationFailedException {
   synchronized (sourceCache) {
     Class answer = sourceCache.get(codeSource.getName());
     if (answer != null) return answer;
     answer = doParseClass(codeSource);
     if (shouldCacheSource) sourceCache.put(codeSource.getName(), answer);
     return answer;
   }
 }
Ejemplo n.º 2
0
  private Class doParseClass(GroovyCodeSource codeSource) {
    validate(codeSource);
    Class answer; // Was neither already loaded nor compiling, so compile and add to cache.
    CompilationUnit unit = createCompilationUnit(config, codeSource.getCodeSource());
    if (recompile != null && recompile || recompile == null && config.getRecompileGroovySource()) {
      unit.addFirstPhaseOperation(
          TimestampAdder.INSTANCE, CompilePhase.CLASS_GENERATION.getPhaseNumber());
    }
    SourceUnit su = null;
    File file = codeSource.getFile();
    if (file != null) {
      su = unit.addSource(file);
    } else {
      URL url = codeSource.getURL();
      if (url != null) {
        su = unit.addSource(url);
      } else {
        su = unit.addSource(codeSource.getName(), codeSource.getScriptText());
      }
    }

    ClassCollector collector = createCollector(unit, su);
    unit.setClassgenCallback(collector);
    int goalPhase = Phases.CLASS_GENERATION;
    if (config != null && config.getTargetDirectory() != null) goalPhase = Phases.OUTPUT;
    unit.compile(goalPhase);

    answer = collector.generatedClass;
    String mainClass = su.getAST().getMainClassName();
    for (Object o : collector.getLoadedClasses()) {
      Class clazz = (Class) o;
      String clazzName = clazz.getName();
      definePackage(clazzName);
      setClassCacheEntry(clazz);
      if (clazzName.equals(mainClass)) answer = clazz;
    }
    return answer;
  }