Class ClassGraph


  • public class ClassGraph
    extends Object
    Uber-fast, ultra-lightweight Java classpath and module path scanner. Scans classfiles in the classpath and/or module path by parsing the classfile binary format directly rather than by using reflection.

    Documentation: https://github.com/lukehutch/fast-classpath-scanner/wiki

    • Constructor Detail

      • ClassGraph

        public ClassGraph()
        Construct a ClassGraph instance.
    • Method Detail

      • getVersion

        public static final String getVersion()
        Get the version number of ClassGraph.
        Returns:
        the ClassGraph version, or "unknown" if it could not be determined.
      • verbose

        public ClassGraph verbose()
        Switches on verbose logging to System.err.
        Returns:
        this (for method chaining).
      • enableClassInfo

        public ClassGraph enableClassInfo()
        Enables the scanning of classfiles, producing ClassInfo objects in the ScanResult.
        Returns:
        this (for method chaining).
      • ignoreClassVisibility

        public ClassGraph ignoreClassVisibility()
        Causes class visibility to be ignored, enabling private, package-private and protected classes to be scanned. By default, only public classes are scanned. (Automatically calls enableClassInfo().)
        Returns:
        this (for method chaining).
      • enableMethodInfo

        public ClassGraph enableMethodInfo()
        Enables the saving of method info during the scan. This information can be obtained using ClassInfo.getMethodInfo() etc. By default, method info is not scanned. (Automatically calls enableClassInfo().)
        Returns:
        this (for method chaining).
      • ignoreMethodVisibility

        public ClassGraph ignoreMethodVisibility()
        Causes method visibility to be ignored, enabling private, package-private and protected methods to be scanned. By default, only public methods are scanned. (Automatically calls enableClassInfo() and enableMethodInfo().)
        Returns:
        this (for method chaining).
      • enableFieldInfo

        public ClassGraph enableFieldInfo()
        Enables the saving of field info during the scan. This information can be obtained using ClassInfo.getFieldInfo(). By default, field info is not scanned. (Automatically calls enableClassInfo().)
        Returns:
        this (for method chaining).
      • ignoreFieldVisibility

        public ClassGraph ignoreFieldVisibility()
        Causes field visibility to be ignored, enabling private, package-private and protected fields to be scanned. By default, only public fields are scanned. (Automatically calls enableClassInfo() and enableFieldInfo().)
        Returns:
        this (for method chaining).
      • enableStaticFinalFieldConstantInitializerValues

        public ClassGraph enableStaticFinalFieldConstantInitializerValues()
        Enables the saving of static final field constant initializer values. By default, constant initializer values are not scanned. Automatically calls enableClassInfo() and enableFieldInfo().
        Returns:
        this (for method chaining).
      • disableRuntimeInvisibleAnnotations

        public ClassGraph disableRuntimeInvisibleAnnotations()
        Causes only runtime visible annotations to be scanned (causes runtime invisible annotations to be ignored). (Automatically calls enableClassInfo().)
        Returns:
        this (for method chaining).
      • disableJarScanning

        public ClassGraph disableJarScanning()
        Disables the scanning of jarfiles.
        Returns:
        this (for method chaining).
      • disableDirScanning

        public ClassGraph disableDirScanning()
        Disables the scanning of directories.
        Returns:
        this (for method chaining).
      • disableModuleScanning

        public ClassGraph disableModuleScanning()
        Disables the scanning of modules.
        Returns:
        this (for method chaining).
      • enableExternalClasses

        public ClassGraph enableExternalClasses()
        Causes ClassGraph to return classes that are not in the whitelisted packages, but that are directly referred to by classes within whitelisted packages as a superclass, implemented interface or annotation. (Automatically calls enableClassInfo().)
        Returns:
        this (for method chaining).
      • initializeLoadedClasses

        public ClassGraph initializeLoadedClasses()
        Causes classes loaded using ClassInfo.loadClass() to be are initialized after class loading (the default is to not initialize classes).
        Returns:
        this (for method chaining).
      • removeTemporaryFilesAfterScan

        public ClassGraph removeTemporaryFilesAfterScan()
        Remove temporary files, including nested jarfiles (jarfiles within jarfiles, which have to be extracted during scanning in order to be read) from their temporary directory as soon as the scan has completed. The default is for temporary files to be removed by the ScanResult finalizer, or on JVM exit.
        Returns:
        this (for method chaining).
      • stripZipSFXHeaders

        public ClassGraph stripZipSFXHeaders()
        Manually strip the self extracting executable header from zipfiles (i.e. anything before the magic marker "PK", e.g. a Bash script added by Spring-Boot). Increases scanning time, since zipfiles have to be opened twice (once as a byte stream, to check if there is an SFX header, then once as a ZipFile, for decompression).

        Should only be needed in rare cases, where you are dealing with jarfiles with prepended (ZipSFX) headers, where your JVM does not already automatically skip forward to the first "PK" marker (most JVMs should do this automatically, so this option should not be needed).

        Returns:
        this (for method chaining).
      • registerClassLoaderHandler

        public ClassGraph registerClassLoaderHandler​(Class<? extends ClassLoaderHandler> classLoaderHandlerClass)
        Register an extra ClassLoaderHandler. Needed if ClassGraph doesn't know how to extract classpath entries from your runtime environment's ClassLoader. See:

        https://github.com/lukehutch/fast-classpath-scanner/wiki/4.-Working-with-nonstandard-ClassLoaders

        Parameters:
        classLoaderHandlerClass - The ClassLoaderHandler class to register.
        Returns:
        this (for method chaining).
      • overrideClasspath

        public ClassGraph overrideClasspath​(String overrideClasspath)
        Override the automatically-detected classpath with a custom path, with path elements separated by File.pathSeparatorChar. Causes system ClassLoaders and the java.class.path system property to be ignored.

        If this method is called, nothing but the provided classpath will be scanned, i.e. this causes ClassLoaders to be ignored, as well as the java.class.path system property.

        Parameters:
        overrideClasspath - The custom classpath to use for scanning, with path elements separated by File.pathSeparatorChar.
        Returns:
        this (for method chaining).
      • overrideClasspath

        public ClassGraph overrideClasspath​(Iterable<?> overrideClasspathElements)
        Override the automatically-detected classpath with a custom path. Causes system ClassLoaders and the java.class.path system property to be ignored. Works for Iterables of any type whose toString() method resolves to a classpath element string, e.g. String, File or Path.

        If this method is called, nothing but the provided classpath will be scanned, i.e. this causes ClassLoaders to be ignored, as well as the java.class.path system property.

        Parameters:
        overrideClasspathElements - The custom classpath to use for scanning, with path elements separated by File.pathSeparatorChar.
        Returns:
        this (for method chaining).
      • overrideClasspath

        public ClassGraph overrideClasspath​(Object... overrideClasspathElements)
        Override the automatically-detected classpath with a custom path. Causes system ClassLoaders and the java.class.path system property to be ignored. Works for arrays of any member type whose toString() method resolves to a classpath element string, e.g. String, File or Path.
        Parameters:
        overrideClasspathElements - The custom classpath to use for scanning, with path elements separated by File.pathSeparatorChar.
        Returns:
        this (for method chaining).
      • filterClasspathElements

        public ClassGraph filterClasspathElements​(ClassGraph.ClasspathElementFilter classpathElementFilter)
        Add a classpath element filter. The provided ClasspathElementFilter should return true if the path string passed to it is a path you want to scan.
        Parameters:
        classpathElementFilter - The filter function to use. This function should return true if the classpath element path should be scanned, and false if not.
        Returns:
        this (for method chaining).
      • addClassLoader

        public ClassGraph addClassLoader​(ClassLoader classLoader)
        Add a ClassLoader to the list of ClassLoaders to scan.

        This call is ignored if overrideClasspath() is also called, or if this method is called before overrideClassLoaders().

        This call is ignored if overrideClasspath() is called.

        Parameters:
        classLoader - The additional ClassLoader to scan.
        Returns:
        this (for method chaining).
      • overrideClassLoaders

        public ClassGraph overrideClassLoaders​(ClassLoader... overrideClassLoaders)
        Completely override (and ignore) system ClassLoaders and the java.class.path system property.

        This call is ignored if overrideClasspath() is called.

        Parameters:
        overrideClassLoaders - The ClassLoaders to scan instead of the automatically-detected ClassLoaders.
        Returns:
        this (for method chaining).
      • ignoreParentClassLoaders

        public ClassGraph ignoreParentClassLoaders()
        Ignore parent classloaders (i.e. only obtain paths to scan from classloader(s), do not also fetch paths from parent classloader(s)).
        Returns:
        this (for method chaining).
      • whitelistPackages

        public ClassGraph whitelistPackages​(String... packageNames)
        Scan one or more specific packages and their sub-packages. (Automatically calls enableClassInfo().)
        Parameters:
        packageNames - The fully-qualified names of packages to scan (using '.' as a separator). May include a glob wildcard ('*').
        Returns:
        this (for method chaining).
      • whitelistPaths

        public ClassGraph whitelistPaths​(String... paths)
        Scan one or more specific paths, and their sub-directories or nested paths.
        Parameters:
        paths - The paths to scan, relative to the package root of the classpath element (with '/' as a separator). May include a glob wildcard ('*').
        Returns:
        this (for method chaining).
      • whitelistPackagesNonRecursive

        public ClassGraph whitelistPackagesNonRecursive​(String... packageNames)
        Scan one or more specific packages, without recursively scanning sub-packages unless they are themselves whitelisted. (Automatically calls enableClassInfo().)

        This may be particularly useful for scanning the package root ("") without recursively scanning everything in the jar, dir or module.

        Parameters:
        packageNames - The fully-qualified names of packages to scan (with '.' as a separator).
        Returns:
        this (for method chaining).
      • whitelistPathsNonRecursive

        public ClassGraph whitelistPathsNonRecursive​(String... paths)
        Scan one or more specific paths, without recursively scanning sub-directories or nested paths unless they are themselves whitelisted.

        This may be particularly useful for scanning the package root ("") without recursively scanning everything in the jar, dir or module.

        Parameters:
        paths - The paths to scan, relative to the package root of the classpath element (with '/' as a separator).
        Returns:
        this (for method chaining).
      • blacklistPackages

        public ClassGraph blacklistPackages​(String... packageNames)
        Prevent the scanning of one or more specific packages and their sub-packages. (Automatically calls enableClassInfo().)
        Parameters:
        packageNames - The fully-qualified names of packages to blacklist (with '.' as a separator). May include a glob wildcard ('*').
        Returns:
        this (for method chaining).
      • blacklistPaths

        public ClassGraph blacklistPaths​(String... paths)
        Prevent the scanning of one or more specific paths and their sub-directories / nested paths.
        Parameters:
        paths - The paths to blacklist (with '/' as a separator). May include a glob wildcard ('*').
        Returns:
        this (for method chaining).
      • whitelistClasses

        public ClassGraph whitelistClasses​(String... classNames)
        Scan one or more specific classes, without scanning other classes in the same package unless the package is itself whitelisted. (Automatically calls enableClassInfo().)
        Parameters:
        classNames - The fully-qualified names of classes to scan (using '.' as a separator).
        Returns:
        this (for method chaining).
      • blacklistClasses

        public ClassGraph blacklistClasses​(String... classNames)
        Specifically blacklist one or more specific classes, preventing them from being scanned even if they are in a whitelisted package. (Automatically calls enableClassInfo().)
        Parameters:
        classNames - The fully-qualified names of classes to blacklist (using '.' as a separator).
        Returns:
        this (for method chaining).
      • whitelistJars

        public ClassGraph whitelistJars​(String... jarLeafNames)
        Whitelist one or more jars. This will cause only the whitelisted jars to be scanned.
        Parameters:
        jarLeafNames - The leafnames of the jars that should be scanned (e.g. "badlib.jar"). May contain a wildcard glob ('*').
        Returns:
        this (for method chaining).
      • blacklistJars

        public ClassGraph blacklistJars​(String... jarLeafNames)
        Blacklist one or more jars, preventing them from being scanned.
        Parameters:
        jarLeafNames - The leafnames of the jars that should not be scanned (e.g. "badlib.jar"). May contain a wildcard glob ('*').
        Returns:
        this (for method chaining).
      • whitelistLibOrExtJars

        public ClassGraph whitelistLibOrExtJars​(String... jarLeafNames)
        Whitelist one or more jars in a JRE/JDK "lib/" or "ext/" directory (these directories are not scanned unless enableSystemPackages() is called, by association with the JRE/JDK).
        Parameters:
        jarLeafNames - The leafnames of the lib/ext jar(s) that should be scanned (e.g. "mylib.jar"). May contain a wildcard glob ('*'). If you call this method with no parameters, all JRE/JDK "lib/" or "ext/" jars will be whitelisted.
        Returns:
        this (for method chaining).
      • blacklistLibOrExtJars

        public ClassGraph blacklistLibOrExtJars​(String... jarLeafNames)
        Blacklist one or more jars in a JRE/JDK "lib/" or "ext/" directory, preventing them from being scanned.
        Parameters:
        jarLeafNames - The leafnames of the lib/ext jar(s) that should not be scanned (e.g. "badlib.jar"). May contain a wildcard glob ('*'). If you call this method with no parameters, all JRE/JDK "lib/" or "ext/" jars will be blacklisted.
        Returns:
        this (for method chaining).
      • whitelistModules

        public ClassGraph whitelistModules​(String... moduleNames)
        Whitelist one or more modules to scan.
        Parameters:
        moduleNames - The names of the modules that should not be scanned. May contain a wildcard glob ('*').
        Returns:
        this (for method chaining).
      • blacklistModules

        public ClassGraph blacklistModules​(String... moduleNames)
        Blacklist one or more modules, preventing them from being scanned.
        Parameters:
        moduleNames - The names of the modules that should not be scanned. May contain a wildcard glob ('*').
        Returns:
        this (for method chaining).
      • enableSystemPackages

        public ClassGraph enableSystemPackages()
        Enables the scanning of system packages (java.*, jdk.*, oracle.*, etc.) -- these are not scanned by default for speed. Calls {#whitelistLibOrExtJars()} with no parameters, to enable scanning of jars in JRE/JDK "lib/" and "ext/" directories. (Also automatically calls enableClassInfo().)
        Returns:
        this (for method chaining).
      • scanAsync

        public void scanAsync​(ExecutorService executorService,
                              int numParallelTasks,
                              ClassGraph.ScanResultProcessor scanResultProcessor,
                              ClassGraph.FailureHandler failureHandler)
        Asynchronously scans the classpath for matching files, and if runAsynchronously is true, also calls any MatchProcessors if a match is identified.
        Parameters:
        executorService - A custom ExecutorService to use for scheduling worker tasks.
        numParallelTasks - The number of parallel tasks to break the work into during the most CPU-intensive stage of classpath scanning. Ideally the ExecutorService will have at least this many threads available.
        scanResultProcessor - A callback to run on successful scan. Passed the ScanResult after asynchronous scanning has completed and MatchProcessors have been run. (If null, throws IllegalArgumentException.)
        failureHandler - A callback to run on failed scan. Passed any Throwable thrown during the scan. (If null, throws IllegalArgumentException.)
      • scanAsync

        public Future<ScanResult> scanAsync​(ExecutorService executorService,
                                            int numParallelTasks)
        Asynchronously scans the classpath for matching files, and calls any MatchProcessors if a match is identified. Returns a Future object immediately after starting the scan. To block on scan completion, get the result of the returned Future. Uses the provided ExecutorService, and divides the work according to the requested degree of parallelism.

        Note on thread safety: MatchProcessors are all run on a separate thread from the thread that calls this method (although the MatchProcessors are all run on one thread). You will need to add your own synchronization logic if MatchProcessors interact with the main thread. See the following for more info:

        https://github.com/lukehutch/fast-classpath-scanner/wiki/1.-Usage#multithreading-issues

        Parameters:
        executorService - A custom ExecutorService to use for scheduling worker tasks.
        numParallelTasks - The number of parallel tasks to break the work into during the most CPU-intensive stage of classpath scanning. Ideally the ExecutorService will have at least this many threads available.
        Returns:
        a Future object, that when resolved using get() yields a new ScanResult object. This ScanResult object contains info about the class graph within whitelisted packages encountered during the scan. Calling get() on this Future object throws InterruptedException if the scanning is interrupted before it completes, or throws ExecutionException if something goes wrong during scanning. If ExecutionException is thrown, and the cause is a MatchProcessorException, then either classloading failed for some class, or a MatchProcessor threw an exception.
      • scan

        public ScanResult scan​(ExecutorService executorService,
                               int numParallelTasks)
        Scans the classpath for matching files, and calls any MatchProcessors if a match is identified. Uses the provided ExecutorService, and divides the work according to the requested degree of parallelism. Blocks and waits for the scan to complete before returning a ScanResult.
        Parameters:
        executorService - A custom ExecutorService to use for scheduling worker tasks. This ExecutorService should start tasks in FIFO order to avoid a deadlock during scan, i.e. be sure to construct the ExecutorService with a LinkedBlockingQueue as its task queue. (This is the default for Executors.newFixedThreadPool().)
        numParallelTasks - The number of parallel tasks to break the work into during the most CPU-intensive stage of classpath scanning. Ideally the ExecutorService will have at least this many threads available.
        Returns:
        a new ScanResult object, containing info about the class graph within whitelisted packages encountered during the scan.
        Throws:
        RuntimeException - if any of the worker threads throws an uncaught exception. (Should not happen, this would indicate a bug in ClassGraph.)
      • scan

        public ScanResult scan​(int numThreads)
        Scans the classpath for matching files, and calls any MatchProcessors if a match is identified. Temporarily starts up a new fixed thread pool for scanning, with the requested number of threads. Blocks and waits for the scan to complete before returning a ScanResult.
        Parameters:
        numThreads - The number of worker threads to start up.
        Returns:
        a new ScanResult object, containing info about the class graph within whitelisted packages encountered during the scan.
        Throws:
        RuntimeException - if any of the worker threads throws an uncaught exception. (Should not happen, this would indicate a bug in ClassGraph.)
      • scan

        public ScanResult scan()
        Scans the classpath for matching files, and calls any MatchProcessors if a match is identified. Temporarily starts up a new fixed thread pool for scanning, with the default number of threads (6). Blocks and waits for the scan to complete before returning a ScanResult.
        Returns:
        a new ScanResult object, containing info about the class graph within whitelisted packages encountered during the scan.
        Throws:
        RuntimeException - if any of the worker threads throws an uncaught exception. (Should not happen, this would indicate a bug in ClassGraph.)
      • getClasspathFiles

        public List<File> getClasspathFiles()
        Returns the list of all unique File objects representing directories or zip/jarfiles on the classpath, in classloader resolution order. Will cause "http://" and "https://" classpath element URLs to be downloaded to a temporary file, and inner zipfiles (jars within jars) to be extracted to temporary files. Classpath elements that do not exist as a file or directory, including JPMS modules that are not backed by a "file:/" URL, are not included in the returned list.
        Returns:
        a List<File> consisting of the unique directories and jarfiles on the classpath, in classpath resolution order.
      • getClasspath

        public String getClasspath()
        Returns the list of all unique File objects representing directories or zip/jarfiles on the classpath, in classloader resolution order, in the form of a classpath path string. Will cause "http://" and "https://" classpath element URLs to be downloaded to a temporary file, and inner zipfiles (jars within jars) to be extracted to temporary files. Classpath elements that do not exist as a file or directory, including JPMS modules that are not backed by a "file:/" URL, are not included in the returned list.
        Returns:
        a classpath path string consisting of the unique directories and jarfiles on the classpath, in classpath resolution order.
      • getClasspathURLs

        public List<URL> getClasspathURLs()
        Returns the list of all unique URL objects representing directories, zip/jarfiles or modules on the classpath, in classloader resolution order. Will cause "http://" and "https://" classpath element URLs to be downloaded to a temporary file, and inner zipfiles (jars within jars) to be extracted to temporary files. Classpath elements representing jarfiles or directories that do not exist are not included in the returned list.
        Returns:
        a classpath path string consisting of the unique directories and jarfiles on the classpath, in classpath resolution order.
      • getModules

        public List<ModuleRef> getModules()
        Returns references for all the visible modules.
        Returns:
        a list of ModuleRef references for all the visible modules.