ClassGraph is an uber-fast, ultra-lightweight, parallelized classpath scanner and module scanner for Java, Scala, Kotlin and other JVM languages.
ClassGraph won a Duke's Choice Award (a recognition of the most useful and/or innovative software in the Java ecosystem) at Oracle Code One 2018. Thanks to all the users who have reported bugs, requested features, offered suggestions, and submitted pull requests to help get ClassGraph to where it is today. |
---|
ClassGraph is now fully stable. This project adheres to the Zero Bugs Commitment. |
---|
ClassGraph has the ability to "invert" the Java class and/or reflection API, or has the ability to index classes and resources. For example, the Java class and reflection API can tell you the superclass of a given class, or the interfaces implemented by a given class, or can give you the list of annotations on a class; ClassGraph can find all classes that extend a given class (all subclasses of a given class), or all classes that implement a given interface, or all classes that are annotated with a given annotation. The Java API can load the content of a resource file with a specific path in a specific ClassLoader, but ClassGraph can find and load all resources in all classloaders with paths matching a given pattern.
The following code prints the name of all classes in the package com.xyz
or its subpackages, anywhere on the classpath or module path, that are annotated with an annotation of the form @com.xyz.Route("/pages/home.html")
, along with the annotation parameter value. This is accomplished without loading or initializing any of the scanned classes.
String pkg = "com.xyz";
String routeAnnotation = pkg + ".Route";
try (ScanResult scanResult =
new ClassGraph()
.verbose() // Log to stderr
.enableAllInfo() // Scan classes, methods, fields, annotations
.whitelistPackages(pkg) // Scan com.xyz and subpackages (omit to scan all packages)
.scan()) { // Start the scan
for (ClassInfo routeClassInfo : scanResult.getClassesWithAnnotation(routeAnnotation)) {
AnnotationInfo routeAnnotationInfo = routeClassInfo.getAnnotationInfo(routeAnnotation);
List<AnnotationParameterValue> routeParamVals = routeAnnotationInfo.getParameterValues();
// @com.xyz.Route has one required parameter
String route = (String) routeParamVals.get(0).getValue();
System.out.println(routeClassInfo.getName() + " is annotated with route " + route);
}
}
The following code finds all JSON files in META-INF/config
in all ClassLoaders or modules, and calls the method readJson(String path, String content)
with the path and content of each file.
try (ScanResult scanResult = new ClassGraph().whitelistPathsNonRecursive("META-INF/config").scan()) {
scanResult.getResourcesWithExtension("json").forEachByteArray((Resource res, byte[] content) -> {
readJson(res.getPath(), new String(content, StandardCharsets.UTF_8));
});
}
See the code examples page for more examples of how to use the ClassGraph API.
ClassGraph provides a number of important capabilities to the JVM ecosystem:
- ClassGraph has the ability to build a model in memory of the entire relatedness graph of all classes, annotations, interfaces, methods and fields that are visible to the JVM. This graph can be queried in a wide range of ways, enabling some degree of metaprogramming in JVM languages -- the ability to write code that analyzes or responds to the properties of other code.
- ClassGraph reads the classfile bytecode format directly, so it can read all information about classes without loading or initializing them.
- ClassGraph is fully compatible with the new JPMS module system (Project Jigsaw / JDK 9+), i.e. it can scan both the traditional classpath and the module path. However, the code is also fully backwards compatible with JDK 7 and JDK 8 (i.e. the code is compiled in Java 7 compatibility mode, and all interaction with the module system is implemented via reflection for backwards compatibility).
- ClassGraph scans the classpath or module path using carefully optimized multithreaded code for the shortest possible scan times, and it runs as close as possible to I/O bandwidth limits, even on a fast SSD.
- ClassGraph handles more classpath specification mechanisms found in the wild than any other classpath scanner, making code that depends upon ClassGraph maximally portable.
- ClassGraph can scan the classpath and module path either at runtime or at build time (e.g. to implement annotation processing for Android).
- ClassGraph can find classes that are duplicated or defined more than once in the classpath or module path, which can help find the cause of strange class resolution behaviors.
- ClassGraph can create GraphViz visualizations of the class graph structure, which can help with code understanding: (click to enlarge | see graph legend here)
Replace X.Y.Z
below with the latest release number. (Alternatively, you could use LATEST
in place of X.Y.Z
instead if you just want to grab the latest version -- although be aware that that may lead to non-reproducible builds, since the ClassGraph version number could increase at any time. You could use dependency locking to address this.)
<dependency>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
<version>X.Y.Z</version>
</dependency>
See instructions for use as a module.
You can get pre-built JARs (usable on JRE 7 or newer) from Sonatype.
ClassGraph must be built on JDK 8 or newer (due to the presence of @FunctionalInterface
annotations on some interfaces), but is built using -target 1.7
for backwards compatibility with JRE 7.
The following commands will build the most recent version of ClassGraph from git master. The compiled package will then be in the "classgraph/target" directory.
git clone https://github.com/classgraph/classgraph.git
cd classgraph
export JAVA_HOME=/usr/java/default # Or similar -- Maven needs JAVA_HOME
./mvnw -Dmaven.test.skip=true package
This will allow you to build a local SNAPSHOT jar in target/
. Alternatively, use ./mvnw -Dmaven.test.skip=true install
to build a SNAPSHOT jar and then copy it into your local repository, so that you can use it in your Maven projects. Note that may need to do ./mvnw dependency:resolve
in your project if you overwrite an older snapshot with a newer one.
./mvnw -U
updates from remote repositories an may overwrite your local artifact. But you can always change the artifactId
or the groupId
of your local ClassGraph build to place your local build artifact in another location within your local repository.
See the wiki for complete documentation and usage information.
ClassGraph was known as FastClasspathScanner prior to version 4. See the porting notes for information on porting from the older FastClasspathScanner API.
- Feel free to subscribe to the ClassGraph-Users email list for updates, or to ask questions.
- There is also a Gitter room for discussion of ClassGraph.
ClassGraph was written by Luke Hutchison (@LH on Twitter).
If ClassGraph is critical to your work, you can help fund further development through the GitHub Sponsors Program.
ClassGraph would not be possible without contributions from numerous users, including in the form of bug reports, feature requests, code contributions, and assistance with testing.
Some other classpath scanning mechanisms include:
- Reflections
- Corn Classpath Scanner
- annotation-detector
- Scannotation
- Sclasner
- Annovention
- ClassIndex (compiletime annotation scanner/processor)
- Jandex (Java annotation indexer, part of Wildfly)
- Spring has built-in classpath scanning
- Hibernate has the class
org.hibernate.ejb.packaging.Scanner
. - extcos -- the Extended Component Scanner
- Javassist
- ObjectWeb ASM
- QDox, a fast Java source parser and indexer
- bndtools, which is able to "crawl"/parse the bytecode of class files to find all imports/dependencies, among other things.
- coffea, a command line tool and Python library for analyzing static dependences in Java bytecode
- org.clapper.classutil.ClassFinder
- com.google.common.reflect.ClassPath
The MIT License (MIT)
Copyright (c) 2019 Luke Hutchison
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.