Package com.subhajit.classbench

Source Code of com.subhajit.classbench.Classpath

package com.subhajit.classbench;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.List;

import com.subhajit.common.classloaders.URLClassLoaderX;
import com.subhajit.common.util.StrUtils;
import com.subhajit.common.util.streams.FileUtils;

/**
* A {@link Classpath} models a set of JAR files and directories containing
* <tt>class</tt> files.
*
* @author sdasgupta
*
*/
public class Classpath {
  private final List<File> elements;

  /**
   * Creates a new {@link Classpath} using the application class loader's
   * files and directories.
   */
  public Classpath() {
    super();
    elements = new ArrayList<File>();
    for (String path : StrUtils.parse(
        System.getProperty("java.class.path"), File.pathSeparator)) {
      File file = new File(path).getAbsoluteFile();
      if (file.exists()) {
        elements.add(file);
      }
    }
  }

  /**
   * Creates a {@link Classpath} containing all directories and JAR files
   * found under all of the given <tt>files</tt>.
   *
   * @param files
   */
  public Classpath(File... files) {
    super();
    elements = new ArrayList<File>();
    for (File file : files) {
      if (file.isFile() && file.getName().endsWith(".jar")) {
        elements.add(file);
      } else if (file.isDirectory()) {
        elements.add(file);
        for (File element : FileUtils.listAllContentsUnder(file)) {
          if (element.isFile() && element.getName().endsWith(".jar")) {
            elements.add(element);
          }
        }
      }
    }
  }

  public URLClassLoader newClassLoader(final ClassLoader parent)
      throws IOException, ClassNotFoundException {
    return new PrivilegedExceptionAction<URLClassLoader>() {
      public URLClassLoader run() throws IOException,
          ClassNotFoundException {
        List<URL> urls = new ArrayList<URL>();
        for (File element : elements) {
          urls.add(element.toURI().toURL());
        }
        return new URLClassLoaderX(urls.toArray(new URL[0]), parent);
      }
    }.run();
  }

  public List<File> getElements() {
    return new ArrayList<File>(elements);
  }
}
TOP

Related Classes of com.subhajit.classbench.Classpath

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.