java.net.URLClassLoader类的使用及代码示例

x33g5p2x  于2022-01-31 转载在 其他  
字(11.0k)|赞(0)|评价(0)|浏览(126)

本文整理了Java中java.net.URLClassLoader类的一些代码示例,展示了URLClassLoader类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。URLClassLoader类的具体详情如下:
包路径:java.net.URLClassLoader
类名称:URLClassLoader

URLClassLoader介绍

[英]This class loader is responsible for loading classes and resources from a list of URLs which can refer to either directories or JAR files. Classes loaded by this URLClassLoader are granted permission to access the URLs contained in the URL search list.
[中]这个类加载器负责从URL列表中加载类和资源,这些URL可以引用目录或JAR文件。此URLClassLoader加载的类被授予访问URL搜索列表中包含的URL的权限。

代码示例

代码示例来源:origin: google/guava

@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_notURLClassLoader_withParentAndGrandParent() throws Exception {
 URL url1 = new URL("file:/a");
 URL url2 = new URL("file:/b");
 URLClassLoader grandParent = new URLClassLoader(new URL[] {url1}, null);
 URLClassLoader parent = new URLClassLoader(new URL[] {url2}, grandParent);
 assertThat(ClassPath.Scanner.getClassPathEntries(new ClassLoader(parent) {}))
   .containsExactly(new File("/a"), grandParent, new File("/b"), parent);
}

代码示例来源:origin: h2oai/h2o-2

public VM(String[] java, String[] args) {
 _args = new ArrayList<String>();
 _args.add(System.getProperty("java.home") + "/bin/java");
 // Iterate on URIs in case jar has been unpacked by Boot
 _args.add("-cp");
 String cp = "";
 for( URL url : ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs() ) {
  try {
   cp += new File(new URI(url.toString())) + File.pathSeparator;
  } catch( URISyntaxException e ) {
   throw Log.errRTExcept(e);
  }
 }
 _args.add(cp);
 _args.addAll(Arrays.asList(java));
 if( args != null )
  _args.addAll(Arrays.asList(args));
}

代码示例来源:origin: google/guava

@Override
 public Class<?> loadClass(String name) throws ClassNotFoundException {
  if (name.startsWith(concurrentPackage)
    // Use other classloader for ListenableFuture, so that the objects can interact
    && !ListenableFuture.class.getName().equals(name)) {
   synchronized (loadedClasses) {
    Class<?> toReturn = loadedClasses.get(name);
    if (toReturn == null) {
     toReturn = super.findClass(name);
     loadedClasses.put(name, toReturn);
    }
    return toReturn;
   }
  }
  return super.loadClass(name);
 }
};

代码示例来源:origin: azkaban/azkaban

@Override
 public Class<?> findClass(final String name) throws ClassNotFoundException {
  try {
   final Class<?> loaded = super.findLoadedClass(name);
   if (loaded != null) {
    return loaded;
   }
   // first try to use the URLClassLoader findClass
   return super.findClass(name);
  } catch (final ClassNotFoundException e) {
   // if that fails, we ask our real parent classloader to load the class (we give up)
   return this.realParent.loadClass(name);
  }
 }
}

代码示例来源:origin: apache/incubator-druid

@Test(timeout = 60_000L)
public void testDeadLock() throws Exception
{
 final URL[] urls = ((URLClassLoader) Granularity.class.getClassLoader()).getURLs();
 final String className = Granularity.class.getCanonicalName();
 for (int i = 0; i < 1000; ++i) {
  final ClassLoader loader = new URLClassLoader(urls, null);
  Assert.assertNotNull(String.valueOf(i), Class.forName(className, true, loader));
 }
}

代码示例来源:origin: org.apache.axis2/axis2-jaxbri

private static void scanEpisodeFile(File jar, SchemaCompiler sc)
    throws BadCommandLineException, IOException {
  URLClassLoader ucl = new URLClassLoader(new URL[]{jar.toURI().toURL()});
  Enumeration<URL> resources = ucl.findResources("META-INF/sun-jaxb.episode");
  while (resources.hasMoreElements()) {
    URL url = resources.nextElement();
    sc.getOptions().addBindFile(new InputSource(url.toExternalForm()));
  }
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

public static String getClassPath() throws IOException {
  ClassLoader cl = MvelTestUtils.class.getClassLoader();
  String classpath = null;
  StringBuilder buffer = new StringBuilder();
  Enumeration<URL> resources = cl.getResources("META-INF/MANIFEST.MF");
  while (resources.hasMoreElements()) {
    Manifest manifest = new Manifest(resources.nextElement().openStream());
    Attributes main = manifest.getMainAttributes();
    String mainClass = main.getValue("Main-Class");
    if ("org.apache.maven.surefire.booter.ForkedBooter".equals(mainClass)) {
      String[] urls = main.getValue("Class-Path").split(" ");
      for (String url : urls) {
        assembleClassPathElement(buffer, new URL(url));
      }
      classpath = cleanUpClassPathString(buffer);
      break;
    }
  }
  if (buffer.length() == 0) {
    for (URL url : ((URLClassLoader) cl).getURLs()) {
      assembleClassPathElement(buffer, url);
    }
    classpath = cleanUpClassPathString(buffer);
  }
  return classpath;
}

代码示例来源:origin: com.github.tcnh/fitnesse-autocomplete-responder

private static List<Class> getClassesFromJar(String jar, String pkg, URLClassLoader classLoader) {
  List<Class> jarClasses = new ArrayList<>();
  try {
    JarFile jarFile = new JarFile(jar);
    Enumeration<JarEntry> e = jarFile.entries();
    URL[] urls = {new URL("jar:file:" + jar + "!/")};
    URLClassLoader cl = new URLClassLoader(urls, classLoader);
    String pkgName;
    while (e.hasMoreElements()) {
      JarEntry je = e.nextElement();
      if (je.isDirectory() || !je.getName().endsWith(".class") || je.getName().contains("$")) {
        continue;
          Class c = cl.loadClass(fqClassName);
          jarClasses.add(c);
        } catch (ClassNotFoundException ex) {

代码示例来源:origin: org.pustefixframework/pustefix-core

URL[] urls = cl.getURLs();
for(URL url: urls) {
  if(url.getProtocol().equals("file")) {
    if(url.getPath().endsWith(".jar")) {
      JarFile file = new JarFile(new File(url.toURI()));
      Enumeration<JarEntry> e = file.entries();
      while(e.hasMoreElements()) {
        JarEntry entry = e.nextElement();
        if(entry.getName().endsWith(".class")) {
          String className = entry.getName();

代码示例来源:origin: cagataygurturk/lambadaframework

private List<Class<? extends Object>> getClassesInJarFile(String jarUrl)
    throws IOException {
  URL[] urls = {new URL("jar:file:" + jarUrl + "!/")};
  JarFile jarFile = new JarFile(jarUrl);
  URLClassLoader cl = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
  Enumeration e = jarFile.entries();
  while (e.hasMoreElements()) {
    JarEntry je = (JarEntry) e.nextElement();
    if (je.isDirectory() || !je.getName().endsWith(".class")) {
      continue;
  jarFile.close();
  cl.close();

代码示例来源:origin: org.openjdk.jol/jol-cli

private Multiset<String> processJAR(String jarName) {
  Multiset<String> shapes = new Multiset<String>();
  try {
    URLClassLoader cl = URLClassLoader.newInstance(new URL[]{new URL("jar:file:" + jarName + "!/")});
    JarFile jarFile = new JarFile(jarName);
    Enumeration e = jarFile.entries();
    while (e.hasMoreElements()) {
      JarEntry je = (JarEntry) e.nextElement();
      String name = je.getName();
      if (je.isDirectory()) continue;
      if (!name.endsWith(".class")) continue;
      String className = name.substring(0, name.length() - 6).replace('/', '.');
      try {
        Class klass = cl.loadClass(className);
        ClassData cd = ClassData.parseClass(klass);
        String shape = parseClassData(cd);
        shapes.add(shape);
      } catch (Error t) {
      } catch (Throwable t) {
        t.printStackTrace();
      }
    }
    jarFile.close();
  } catch (Exception t) {
    // ignore
  }
  return shapes;
}

代码示例来源:origin: ridencww/goldengine

URL[] urls = { new URL("jar:file:/" + jarFile.getName() + "!/")};
URLClassLoader loader = URLClassLoader.newInstance(urls, Thread.currentThread().getContextClassLoader());
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
  JarEntry entry = entries.nextElement();
  if (!entry.isDirectory()) {
    String className = entry.getName().replace('/', '.');
      if (className.endsWith(".class") && !className.contains("$")) {
        className = className.substring(0, className.lastIndexOf('.'));
        Class clazz = loader.loadClass(className);
        if (!classes.contains(clazz)) { //Needed to handle a bug in Maven that causes duplicate files to be jarred.
          classes.add(loader.loadClass(className));

代码示例来源:origin: stackoverflow.com

try {
      c = findClass(name);
    } catch (ClassNotFoundException e) {
  url = findResource(name);
  if (url == null) {
  systemUrls = system.getResources(name);
Enumeration<URL> localUrls = findResources(name);
Enumeration<URL> parentUrls = null;
if (getParent() != null) {
  while(systemUrls.hasMoreElements()) {
    urls.add(systemUrls.nextElement());
  while (localUrls.hasMoreElements()) {
    urls.add(localUrls.nextElement());
URL url = getResource(name);
try {
  return url != null ? url.openStream() : null;
} catch (IOException e) {

代码示例来源:origin: org.kantega.openaksess/openaksess-core

private void closeClassLoader(ClassLoader classLoader) {
  if(classLoader instanceof URLClassLoader) {
    URL[] urls = ((URLClassLoader) classLoader).getURLs();
    Set<JarFile> closables = new LinkedHashSet<>();
    for(URL url : urls) {
      if(url.getFile().endsWith(".jar")) {
        try {
          URL jarURL = new URL("jar:" + url.toExternalForm() + "!/");
          JarURLConnection urlConnection = (JarURLConnection) jarURL.openConnection();
          JarFile jarFile = urlConnection.getJarFile();
          closables.add(jarFile);
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
    for(JarFile file : closables) {
      try {
        file.close();
      } catch (IOException e) {
        log.error("", e);
      }
    }
  }
}

代码示例来源:origin: br.com.anteros/Anteros-Core

private static Set<URL> findRootsByLoader(ClassLoader loader) {
  Set<URL> urls = new HashSet<URL>();
  if (loader instanceof URLClassLoader) {
    URLClassLoader urlLoader = (URLClassLoader) loader;
    urls.addAll(Arrays.asList(urlLoader.getURLs()));
  } else {
    Enumeration<URL> urlEnum;
    try {
      urlEnum = loader.getResources("");
      while (urlEnum.hasMoreElements()) {
        URL url = urlEnum.nextElement();
        if(url.getProtocol().startsWith("bundleresource")){
          continue;
        }
        urls.add(url);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return urls;
}

代码示例来源:origin: eclipse-vertx/vert.x

/**
 * Creates a classloader respecting the classpath option.
 *
 * @return the classloader.
 */
protected synchronized ClassLoader createClassloader() {
 URL[] urls = classpath.stream().map(path -> {
  File file = new File(path);
  try {
   return file.toURI().toURL();
  } catch (MalformedURLException e) {
   throw new IllegalStateException(e);
  }
 }).toArray(URL[]::new);
 return new URLClassLoader(urls, this.getClass().getClassLoader());
}

代码示例来源:origin: net.java.dev.jna/jna

String path = System.getProperty("java.class.path");
  if (loader instanceof URLClassLoader) {
    path = Arrays.asList(((URLClassLoader)loader).getURLs()).toString();
if (url.getProtocol().toLowerCase().equals("file")) {
  try {
    lib = new File(new URI(url.toString()));
    lib = new File(url.getPath());

代码示例来源:origin: net.jangaroo/exml-compiler

public ExmlToMxml(ConfigClassRegistry configClassRegistry) {
 this.configClassRegistry = configClassRegistry;
 if (configClassRegistry.getConfig().getExtAsJar() != null) {
  try {
   resourceClassLoader = new URLClassLoader(new URL[]{
       new URL("jar:" + configClassRegistry.getConfig().getExtAsJar().toURI().toString() + "!/")
   });
  } catch (IOException e) {
   throw new ExmlcException("Unable to configure resource class loader", e);
  }
 }
}

代码示例来源:origin: org.eclipse.jetty/jetty-webapp

URL[] urls = ((URLClassLoader)loader).getURLs();
if (urls != null)
      containerUris.add(u.toURI());
      containerUris.add(new URI(u.toString().replaceAll(" ", "%20")));

代码示例来源:origin: org.scala-tools/maven-scala-plugin

private URLClassLoader createScriptClassloader(File scriptDir,
    Set<String> classpath) throws MalformedURLException {
  List<URL> urls = new ArrayList<URL>();
  // add the script directory to the classpath
  urls.add(scriptDir.toURI().toURL());
  for (String string : classpath) {
    urls.add(new URL("file://" + string));
  }
  URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls
      .size()]), getClass().getClassLoader());
  return loader;
}

相关文章