Class ClassPath

java.lang.Object
com.google.common.reflect.ClassPath

public final class ClassPath extends Object
Scans the source of a ClassLoader and finds all loadable classes and resources.

Prefer alternatives to classpath scanning

Runtime classpath scanning is expensive because it traverses the entire transitive classpath, which can cause performance issues such as startup latency regressions. (It also does not support Android.) Before scanning the classpath at runtime, consider whether your use case can be solved with compile-time or static mechanisms:

  • Compile-time service registration / annotation processors (e.g., @AutoService)
  • Dependency injection (e.g., Dagger, Guice)
  • Explicit static registries or configuration
  • Compile-time classpath scanning, such as that of ClassGraph, but compile-time scanning is likewise costly, so prefer the other options when possible

Limitations of ClassPath (for those who do need classpath scanning)

In the case of directory classloaders, symlinks are supported but cycles are not traversed. This guarantees discovery of each unique loadable resource. However, not all possible aliases for resources on cyclic paths will be listed.

Since:
14.0
Author:
Ben Yu
  • Method Details

    • from

      public static ClassPath from(ClassLoader classloader) throws IOException
      Returns a ClassPath representing all classes and resources loadable from classloader and its ancestor class loaders.

      Warning: ClassPath can find classes and resources only from:

      Throws:
      IOException - if the attempt to read class path resources (jar files or directories) failed.
    • getResources

      public ImmutableSet<ClassPath.ResourceInfo> getResources()
      Returns all resources loadable from the current class path, including the class files of all loadable classes but excluding the "META-INF/MANIFEST.MF" file.
    • getAllClasses

      public ImmutableSet<ClassPath.ClassInfo> getAllClasses()
      Returns all classes loadable from the current class path.
      Since:
      16.0
    • getTopLevelClasses

      public ImmutableSet<ClassPath.ClassInfo> getTopLevelClasses()
      Returns all top level classes loadable from the current class path. Note that "top-level-ness" is determined heuristically by class name (see ClassPath.ClassInfo.isTopLevel()).
    • getTopLevelClasses

      public ImmutableSet<ClassPath.ClassInfo> getTopLevelClasses(String packageName)
      Returns all top level classes whose package name is packageName.
    • getTopLevelClassesRecursive

      public ImmutableSet<ClassPath.ClassInfo> getTopLevelClassesRecursive(String packageName)
      Returns all top level classes whose package name is packageName or starts with packageName followed by a '.'.