Repository navigation
ClassGraph API
See also the code examples page.
- General usage pattern
- What all the info lists have in common
- Shared supertypes
- API index
- The other libraries
-
Create a
new ClassGraph()instance, and configure it for scanning:-
Say what to scan -- nothing is scanned unless it is enabled. Call
.enableClasspath()for the classpath of every classloader that can be found, and.enableNonSystemModules()for the modules of the visible module layers; or use the varargs forms (.enableClassLoaders(...),.enableClasspathEntries(...),.enableModuleLayers(...)) to scan exactly what you name, and nothing from the environment. - Optionally call
.verbose()to enable verbose logging to stderr. - Enable classfile scanning, if you want to scan classes: call
.enableClassInfo(), and add.enableMethodInfo(),.enableFieldInfo()and/or.enableAnnotationInfo()alongside it for the parts of a classfile you want read. All configuration is explicit -- no configuration method turns on another one, and an option that only modifies another option (such as.ignoreMethodVisibility(), which modifies.enableMethodInfo()) is refused by.scan()if the option it modifies was not enabled too. - Call
.acceptPackages(String... packages)to accept specific packages to scan, or.acceptPaths(String... paths)if you only want to scan resources and not classes. If you don't call either of these methods, then all packages or paths will be scanned.
-
Say what to scan -- nothing is scanned unless it is enabled. Call
-
Start the scan, by calling
.scan(), to produce aScanResultobject.💡 The
ScanResultshould be assigned in a try-with-resources block or equivalent. SeeScanResultlifecycle. -
Query the
ScanResultobject: (theScanResultobject can be queried repeatedly without re-running the scan)-
For class scan results: Call methods such as
.getAllClasses(),.getAllInterfaces()etc. to getClassInfoListlists ofClassInfoobjects for classes of interest- Query the
ClassInfoobjects for class properties or class relationships of interest.- Call
ClassInfo#getMethodInfo()to get info on the methods of the class as aMethodInfoListofMethodInfoobjects.- Call
MethodInfo#getParameterInfo()to get info on the parameters of a method as aListofMethodParameterInfoobjects, one per parameter. - Call
MethodInfo#getAllAnnotationInfo()to get the annotations on a method as anAnnotationInfoListofAnnotationInfoobjects.
- Call
- Call
ClassInfo#getFieldInfo()to get info on the fields of a class as aFieldInfoListofFieldInfoobjects.- Call
FieldInfo#getAllAnnotationInfo()to get the annotations on a field as anAnnotationInfoListofAnnotationInfoobjects.
- Call
- Call
ClassInfo#getAllAnnotationInfo()to get the annotations on a class as anAnnotationInfoListofAnnotationInfoobjects.
💡 Every annotation getter comes in an
Allform and aDirectform. TheAllform includes meta-annotations -- the annotations on the element's own annotations, transitively -- and, for a class, any@Inheritedannotations on its superclasses. TheDirectform includes only the annotations written on the element itself. - Call
-
ClassInfoListlists can be filtered using.filter(predicateFunction)or combined using.union(ClassInfoList... others),.intersect(ClassInfoList... others), or.exclude(ClassInfoList other), to return a newClassInfoListrepresenting the predicate-filtered subset, union, intersection or set difference respectively.
- Query the
-
And/or for resource scan results: Call methods such as
.getAllResources(),.getResourcesWithPath(path),.getResourcesWithExtension(ext)etc. to getResourceListlists ofResource(file) objects matching a given path or filename pattern.- Call
ResourceList#forEachByteArray(ByteArrayConsumer),forEachInputStream(InputStreamConsumer)orforEachByteBuffer(ByteBufferConsumer)to read eachResourcein turn and pass its content to your code. A stream or buffer is closed when your code returns.
- Call
-
For class scan results: Call methods such as
You can scan either at runtime (the usual case), or at build time, for faster startup, or for Android, which does not use the standard Java classfile format.
See the code examples page for specific examples of how to use the ClassGraph API.
Every list of scan results -- ClassInfoList, MethodInfoList, FieldInfoList, AnnotationInfoList, AnnotationParameterValueList, PackageInfoList, ModuleInfoList and ResourceList -- is an unmodifiable List, so it can be iterated with a for-each loop, streamed, or passed anywhere a List is expected. They also share the following.
-
A list that came from a scan is unmodifiable.
add,remove,set,sort,clearand every other mutation method throwUnsupportedOperationException, whether or not the call would actually have changed anything. To sort or modify the contents, copy the list first:List<ClassInfo> sorted = new ArrayList<>(scanResult.getAllClasses()); sorted.sort(Comparator.comparing(ClassInfo::getSimpleName));
The public
Collectionconstructor of each*InfoListalso creates an unmodifiable snapshot. Build the elements in anArrayList(or another mutable collection), then pass the completed collection to the*InfoListconstructor. Later changes to the source collection do not change the*InfoList. -
Lookup by name:
.get(String name)returns the entry with that name, or null if there is none, and.containsName(String name)tests for it without fetching it..asMap()returns the whole list as aMap<String, ...>, sorted by name, if you need to look up many names.-
MethodInfoListis the exception, because a method name can be overloaded: there,.get(String name)returns aMethodInfoListof all methods with that name, and.getSingleMethod(String name)returns the single method with that name, or null if there is none, or throwsIllegalArgumentExceptionif the name is overloaded. -
ResourceListis keyed by resource path rather than by name, and has.getPaths(),.getURIs()and.getURLs()in place of the name methods below.
-
-
Names and strings:
.getNames()returns the name of every entry as aList<String>..getAsStrings()returns thetoString()of every entry -- for a method or field list, that is the full declaration, including modifiers, generic types and annotations..getAsStringsWithSimpleNames()does the same using simple class names rather than fully-qualified ones, which is easier to read. -
.filter(...)returns a new list holding just the entries that your predicate accepts (on every list butAnnotationParameterValueList).ClassInfoListadditionally has.union(...),.intersect(...)and.exclude(...)for combining lists. -
.emptyList()is a static method on every one of these classes, returning a shared unmodifiable empty list, which is what a query with no results gives you. No ClassGraph method ever returns null in place of an empty list, so there is no need to null-check a returned list. -
Order:
ClassInfoList,PackageInfoListandModuleInfoListare sorted by name, except where the order carries meaning:ClassInfo#getAllSuperclasses()is listed from the direct superclass upward,ClassInfo#getEnclosingClasses()from the innermost class outward,ClassInfo#getAllSuperinterfaces()in the order the interfaces are declared and inherited, andMethodInfo#getThrownExceptions()in the order of thethrowsclause. The methods and fields declared by a class are listed in the order the classfile declares them, which is the orderjavapshows them in.
Four types exist so that code can be written against what several result types have in common, rather than against each of them separately:
-
HasNameis implemented by everything with a name:ClassInfo,MethodInfo,FieldInfo,AnnotationInfo,AnnotationParameterValue,PackageInfoandModuleInfo. It declares only.getName(), and it is what makes the name lookups above possible for every info list. -
HasAnnotationsis implemented by everything that can be annotated:ClassInfo,ClassMemberInfo(the superclass ofMethodInfoandFieldInfo),MethodParameterInfo,PackageInfoandModuleInfo. It declares the whole annotation-query API --.getAllAnnotationInfo(),.getDirectAnnotationInfo(), their by-name and by-Classforms, theRepeatableforms, and.hasAnnotation(...)-- so one method can take aHasAnnotationsand read annotations off a class, a method, a field, a parameter, a package or a module alike. -
ClassMemberInfois the common superclass ofMethodInfoandFieldInfo. It issealed, and these are its only subclasses, so a patternswitch(Java 21 or newer) over aClassMemberInfothat listsMethodInfoandFieldInfoneeds nodefaultcase. It holds everything a method and a field have in common: the declaring class, the name, the modifiers (.getModifiers(),.isPublic(),.isStatic(), ...), the type descriptor and type signature, the annotations, and.getClassDependencies(). -
HierarchicalTypeSignatureis the root of the type signature hierarchy. It declares.getTypeAnnotationInfo(), and the.toString()/.toStringWithSimpleNames()pair that renders any type signature back into Java source form.
- Configuring the
ClassGraphinstance - Starting the scan
- Processing the result of the scan:
-
Classes:
-
Classes
-
ClassInfo- (The class metadata class. Use
ClassInfoobjects to obtain references toAnnotationInfo,MethodInfo,MethodParameterInfoorFieldInfoobjects.)
- (The class metadata class. Use
ClassInfoList
-
-
Methods
-
MethodInfo- (The method metadata class. Use
MethodInfoobjects to obtain references toMethodParameterInfoobjects, and/orAnnotationInfoobjects for method annotations.)
- (The method metadata class. Use
-
MethodParameterInfo- (The method parameter metadata class. Use
MethodParameterInfoobjects to obtain references toAnnotationInfoobjects for method parameter annotations.)
- (The method parameter metadata class. Use
MethodInfoList
-
-
Fields
-
FieldInfo- (The field metadata class. Use
FieldInfoobjects to obtain references toAnnotationInfoobjects for field annotations.)
- (The field metadata class. Use
FieldInfoList
-
-
Annotations
-
AnnotationInfo- (The annotation metadata class. Use
AnnotationInfoobjects to obtain references toAnnotationParameterValueobjects for parameter values for specific annotation instances.)
- (The annotation metadata class. Use
AnnotationParameterValueAnnotationEnumValueAnnotationClassRefAnnotationInfoList
-
- Type signatures
- Packages:
- Modules:
-
Classes
-
Resources:
-
Resource- (The main metadata class for resource files encountered in accepted packages or paths during a scan.)
ResourceList
-
Two of the libraries that ClassGraph is built out of have an API of their own, and can be used without scanning anything. There is also a library that renders a scan result as a graph. See the five libraries for how they fit together.
- Vfs API -- read directories, jarfiles and modules through one read-only virtual filesystem, without scanning anything.
- Classpath API -- find the classpath elements and modules a JVM loads from, without scanning them.
-
GraphViz API -- render a scan result as a GraphViz
.dotfile.