Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2012 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.reflect;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.io.File;
 import java.net.URI;
 import java.net.URL;
 import java.util.Map;
 
 import  javax.annotation.Nullable;

Scans the source of a ClassLoader and finds all the classes loadable.

Author(s):
Ben Yu
Since:
14.0
 
 public final class ClassPath {
 
   private static final Logger logger = Logger.getLogger(ClassPath.class.getName());

  
Separator for the Class-Path manifest attribute value in jar files.
 
   private static final Splitter CLASS_PATH_ATTRIBUTE_SEPARATOR =
       Splitter.on(" ").omitEmptyStrings();
 
   private static final String CLASS_FILE_NAME_EXTENSION = ".class";
 
   private final ImmutableSet<ResourceInforesources;
 
   private ClassPath(ImmutableSet<ResourceInforesources) {
     this. = resources;
   }

  
Returns a ClassPath representing all classes and resources loadable from classloader and its parent class loaders.

Currently only URLClassLoader and only file:// urls are supported.

Throws:
IOException if the attempt to read class path resources (jar files or directories) failed.
 
   public static ClassPath from(ClassLoader classloaderthrows IOException {
     ImmutableSortedSet.Builder<ResourceInforesources =
         new ImmutableSortedSet.Builder<ResourceInfo>(Ordering.usingToString());
     for (Map.Entry<URIClassLoaderentry : getClassPathEntries(classloader).entrySet()) {
       browse(entry.getKey(), entry.getValue(), resources);
     }
     return new ClassPath(resources.build());
   }

  
Returns all resources loadable from the current class path, including the class files of all loadable classes.
 
     return ;
   }

  
Returns all top level classes loadable from the current class path.
 
     ImmutableSet.Builder<ClassInfobuilder = ImmutableSet.builder();
     for (ResourceInfo resource : ) {
       if (resource instanceof ClassInfo) {
        builder.add((ClassInforesource);
      }
    }
    return builder.build();
  }

  
Returns all top level classes whose package name is packageName.
  public ImmutableSet<ClassInfogetTopLevelClasses(String packageName) {
    checkNotNull(packageName);
    ImmutableSet.Builder<ClassInfobuilder = ImmutableSet.builder();
    for (ClassInfo classInfo : getTopLevelClasses()) {
      if (classInfo.getPackageName().equals(packageName)) {
        builder.add(classInfo);
      }
    }
    return builder.build();
  }

  
Returns all top level classes whose package name is packageName or starts with packageName followed by a '.'.
    checkNotNull(packageName);
    String packagePrefix = packageName + '.';
    ImmutableSet.Builder<ClassInfobuilder = ImmutableSet.builder();
    for (ClassInfo classInfo : getTopLevelClasses()) {
      if (classInfo.getName().startsWith(packagePrefix)) {
        builder.add(classInfo);
      }
    }
    return builder.build();
  }

  
Represents a class path resource that can be either a class file or any other resource file loadable from the class path.

Since:
14.0
  @Beta
  public static class ResourceInfo {
    private final String resourceName;
    final ClassLoader loader;
    static ResourceInfo of(String resourceNameClassLoader loader) {
      if (resourceName.endsWith() && !resourceName.contains("$")) {
        return new ClassInfo(resourceNameloader);
      } else {
        return new ResourceInfo(resourceNameloader);
      }
    }
  
    ResourceInfo(String resourceNameClassLoader loader) {
      this. = checkNotNull(resourceName);
      this. = checkNotNull(loader);
    }

    
Returns the url identifying the resource.
    public final URL url() {
          "Failed to load resource: %s");
    }

    
Returns the fully qualified name of the resource. Such as "com/mycomp/foo/bar.txt".
    public final String getResourceName() {
      return ;
    }
    @Override public int hashCode() {
      return .hashCode();
    }
    @Override public boolean equals(Object obj) {
      if (obj instanceof ResourceInfo) {
        ResourceInfo that = (ResourceInfoobj;
        return .equals(that.resourceName)
            &&  == that.loader;
      }
      return false;
    }
    @Override public String toString() {
      return ;
    }
  }

  
Represents a class that can be loaded through load.

Since:
14.0
  @Beta
  public static final class ClassInfo extends ResourceInfo {
    private final String className;
    ClassInfo(String resourceNameClassLoader loader) {
      super(resourceNameloader);
      this. = getClassName(resourceName);
    }

    
Returns the package name of the class, without attempting to load the class.
    public String getPackageName() {
      return Reflection.getPackageName();
    }

    
Returns the simple name of the underlying class as given in the source code.
    public String getSimpleName() {
      String packageName = getPackageName();
      if (packageName.isEmpty()) {
        return ;
      }
      // Since this is a top level class, its simple name is always the part after package name.
      return .substring(packageName.length() + 1);
    }

    
Returns the fully qualified name of the class.
    public String getName() {
      return ;
    }

    
Loads (but doesn't link or initialize) the class.
    public Class<?> load() {
      try {
        return .loadClass();
      } catch (ClassNotFoundException e) {
        // Shouldn't happen, since the class name is read from the class path.
        throw new IllegalStateException(e);
      }
    }
    @Override public String toString() {
      return ;
    }
  }
      ClassLoader classloader) {
    LinkedHashMap<URIClassLoaderentries = Maps.newLinkedHashMap();
    // Search parent first, since it's the order ClassLoader#loadClass() uses.
    ClassLoader parent = classloader.getParent();
    if (parent != null) {
      entries.putAll(getClassPathEntries(parent));
    }
    if (classloader instanceof URLClassLoader) {
      URLClassLoader urlClassLoader = (URLClassLoaderclassloader;
      for (URL entry : urlClassLoader.getURLs()) {
        URI uri;
        try {
          uri = entry.toURI();
        } catch (URISyntaxException e) {
          throw new IllegalArgumentException(e);
        }
        if (!entries.containsKey(uri)) {
          entries.put(uriclassloader);
        }
      }
    }
    return ImmutableMap.copyOf(entries);
  }
  private static void browse(
      URI uriClassLoader classloaderImmutableSet.Builder<ResourceInforesources)
      throws IOException {
    if (uri.getScheme().equals("file")) {
      browseFrom(new File(uri), classloaderresources);
    }
  }
  @VisibleForTesting static void browseFrom(
      File fileClassLoader classloaderImmutableSet.Builder<ResourceInforesources)
      throws IOException {
    if (!file.exists()) {
      return;
    }
    if (file.isDirectory()) {
      browseDirectory(fileclassloaderresources);
    } else {
      browseJar(fileclassloaderresources);
    }
  }
  private static void browseDirectory(
      File directoryClassLoader classloaderImmutableSet.Builder<ResourceInforesources) {
    browseDirectory(directoryclassloader""resources);
  }
  private static void browseDirectory(
      File directoryClassLoader classloaderString packagePrefix,
      ImmutableSet.Builder<ResourceInforesources) {
    for (File f : directory.listFiles()) {
      String name = f.getName();
      if (f.isDirectory()) {
        browseDirectory(fclassloaderpackagePrefix + name + "/"resources);
      } else {
        String resourceName = packagePrefix + name;
        resources.add(ResourceInfo.of(resourceNameclassloader));
      }
    }
  }
  private static void browseJar(
      File fileClassLoader classloaderImmutableSet.Builder<ResourceInforesources)
      throws IOException {
    JarFile jarFile;
    try {
      jarFile = new JarFile(file);
    } catch (IOException e) {
      // Not a jar file
      return;
    }
    try {
      for (URI uri : getClassPathFromManifest(filejarFile.getManifest())) {
        browse(uriclassloaderresources);
      }
      Enumeration<JarEntryentries = jarFile.entries();
      while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (entry.isDirectory() || entry.getName().startsWith("META-INF/")) {
          continue;
        }
        resources.add(ResourceInfo.of(entry.getName(), classloader));
      }
    } finally {
      try {
        jarFile.close();
      } catch (IOException ignored) {}
    }
  }

  
Returns the class path URIs specified by the Class-Path manifest attribute, according to JAR File Specification. If manifest is null, it means the jar file has no manifest, and an empty set will be returned.
      File jarFile, @Nullable Manifest manifest) {
    if (manifest == null) {
      return ImmutableSet.of();
    }
    ImmutableSet.Builder<URIbuilder = ImmutableSet.builder();
    String classpathAttribute = manifest.getMainAttributes().getValue("Class-Path");
    if (classpathAttribute != null) {
      for (String path : .split(classpathAttribute)) {
        URI uri;
        try {
          uri = getClassPathEntry(jarFilepath);
        } catch (URISyntaxException e) {
          // Ignore bad entry
          .warning("Invalid Class-Path entry: " + path);
          continue;
        }
        builder.add(uri);
      }
    }
    return builder.build();
  }

  
Returns the absolute uri of the Class-Path entry value as specified in JAR File Specification. Even though the specification only talks about relative urls, absolute urls are actually supported too (for example, in Maven surefire plugin).
  @VisibleForTesting static URI getClassPathEntry(File jarFileString path)
      throws URISyntaxException {
    URI uri = new URI(path);
    if (uri.isAbsolute()) {
      return uri;
    } else {
      return new File(jarFile.getParentFile(), path.replace('/'.)).toURI();
    }
  }
  @VisibleForTesting static String getClassName(String filename) {
    int classNameEnd = filename.length() - .length();
    return filename.substring(0, classNameEnd).replace('/''.');
  }
New to GrepCode? Check out our FAQ X