Пример #1
0
  /**
   * Initializes default class loader. It inherits from classloader, which was used to load this
   * task, therefore build-in classes and resources are loaded automatically.
   *
   * <p>Notice: task's classpath has priority over default classpath, therefore we are able to
   * easily override resources (templates)
   */
  protected void initClassloader() {
    // NOTICE: we should use the same classloader, which was used to load this task
    // otherwise we won't be able to cast instances
    // (that were loaded via different class loaders)

    // we are introducting workaround,
    // that tries to add classpath for current task to original class loader
    // and stores original classpath
    // after the task is executed, classpath is restored

    ClassLoader classLoader = getClass().getClassLoader();
    if (classLoader instanceof AntClassLoader) {
      // add defined classpath
      AntClassLoader antClassLoader = (AntClassLoader) classLoader;
      antClassLoader.setParentFirst(false);
      antClassLoader.setProject(getProject());
      savedClasspath = antClassLoader.getClasspath();

      Path cp = getClasspath();
      // add defined classpath to original path
      cp.add(new Path(getProject(), savedClasspath));
      antClassLoader.setClassPath(cp);
    } else {
      // create new class loader
      classLoader =
          new AntClassLoader(getClass().getClassLoader(), getProject(), getClasspath(), false);
    }

    // set this class loader as new class loader for whole thread
    // ContextClassLoader is used in StringTemplate's PathGroupLoader and other classes
    Thread.currentThread().setContextClassLoader(classLoader);
  }
Пример #2
0
 /** Restores default class loader. */
 protected void restoreClassloader() {
   ClassLoader classLoader = getClass().getClassLoader();
   if (classLoader instanceof AntClassLoader && savedClasspath != null) {
     AntClassLoader antClassLoader = (AntClassLoader) classLoader;
     antClassLoader.setClassPath(new Path(getProject(), savedClasspath));
     savedClasspath = null;
   }
 }