Top Description Inners Fields Constructors Methods
com.google.common.reflect

public final Class ClassPath

extends Object
Class Inheritance
Annotations
@ElementTypesAreNonnullByDefault
Static Imports
com.google.common.base.Preconditions.checkArgument, .Preconditions.checkNotNull, .StandardSystemProperty.JAVA_CLASS_PATH, .StandardSystemProperty.PATH_SEPARATOR, java.util.logging.Level.WARNING

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

Prefer ClassGraph over ClassPath

We recommend using ClassGraph instead of ClassPath. ClassGraph improves upon ClassPath in several ways, including addressing many of its limitations. Limitations of ClassPath include:

ClassPath and symlinks

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.

Author
Ben Yu
Since
14.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
ClassPath.ClassInfo

Represents a class that can be loaded through load.

pack-priv static class
ClassPath.LocationInfo

Represents a single location (a directory or a jar file) in the class path and is responsible for scanning resources from this location.

public static class
ClassPath.ResourceInfo

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

Field Summary

Modifier and TypeField and Description
private static final String
private static final Splitter
CLASS_PATH_ATTRIBUTE_SEPARATOR

Separator for the Class-Path manifest attribute value in jar files.

private static final Logger
private final ImmutableSet<ClassPath.ResourceInfo>

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static ClassPath
from(ClassLoader classloader)

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

public ImmutableSet<ClassPath.ClassInfo>
getAllClasses()

Returns all classes loadable from the current class path.

private static ImmutableList<URL>
pack-priv static String
getClassName(String filename)

pack-priv static ImmutableMap<File, ClassLoader>
pack-priv static URL
getClassPathEntry(File jarFile, String path)

Returns the absolute uri of the Class-Path entry value as specified in JAR File Specification.

pack-priv static ImmutableSet<File>
getClassPathFromManifest(File jarFile, Manifest manifest)

Returns the class path URIs specified by the Class-Path manifest attribute, according to JAR File Specification.

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.

public ImmutableSet<ClassPath.ClassInfo>
getTopLevelClasses()

Returns all top level classes loadable from the current class path.

public ImmutableSet<ClassPath.ClassInfo>
getTopLevelClasses(String packageName)

Returns all top level classes whose package name is packageName.

public ImmutableSet<ClassPath.ClassInfo>
getTopLevelClassesRecursive(String packageName)

Returns all top level classes whose package name is packageName or starts with packageName followed by a '.'.

pack-priv static ImmutableSet<ClassPath.LocationInfo>
locationsFrom(ClassLoader classloader)

Returns all locations that classloader and parent loaders load classes and resources from.

pack-priv static ImmutableList<URL>
parseJavaClassPath()

Returns the URLs in the class path specified by the java.class.path system property.

pack-priv static File
toFile(URL url)

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

CLASS_FILE_NAME_EXTENSIONback to summary
private static final String CLASS_FILE_NAME_EXTENSION
CLASS_PATH_ATTRIBUTE_SEPARATORback to summary
private static final Splitter CLASS_PATH_ATTRIBUTE_SEPARATOR

Separator for the Class-Path manifest attribute value in jar files.

loggerback to summary
private static final Logger logger
resourcesback to summary
private final ImmutableSet<ClassPath.ResourceInfo> resources

Constructor Detail

ClassPathback to summary
private ClassPath(ImmutableSet<ClassPath.ResourceInfo> resources)

Method Detail

fromback to summary
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:

Exceptions
IOException:
if the attempt to read class path resources (jar files or directories) failed.
getAllClassesback to summary
public ImmutableSet<ClassPath.ClassInfo> getAllClasses()

Returns all classes loadable from the current class path.

Since
16.0
getClassLoaderUrlsback to summary
private static ImmutableList<URL> getClassLoaderUrls(ClassLoader classloader)
getClassNameback to summary
pack-priv static String getClassName(String filename)
Annotations
@VisibleForTesting
getClassPathEntriesback to summary
pack-priv static ImmutableMap<File, ClassLoader> getClassPathEntries(ClassLoader classloader)
Annotations
@VisibleForTesting
getClassPathEntryback to summary
pack-priv static URL getClassPathEntry(File jarFile, String path) throws MalformedURLException

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).

Annotations
@VisibleForTesting
getClassPathFromManifestback to summary
pack-priv static ImmutableSet<File> getClassPathFromManifest(File jarFile, Manifest manifest)

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.

Annotations
@VisibleForTesting
getResourcesback to summary
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.

getTopLevelClassesback to summary
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 ClassInfo#isTopLevel).

getTopLevelClassesback to summary
public ImmutableSet<ClassPath.ClassInfo> getTopLevelClasses(String packageName)

Returns all top level classes whose package name is packageName.

getTopLevelClassesRecursiveback to summary
public ImmutableSet<ClassPath.ClassInfo> getTopLevelClassesRecursive(String packageName)

Returns all top level classes whose package name is packageName or starts with packageName followed by a '.'.

locationsFromback to summary
pack-priv static ImmutableSet<ClassPath.LocationInfo> locationsFrom(ClassLoader classloader)

Returns all locations that classloader and parent loaders load classes and resources from. Callers can scan individual locations selectively or even in parallel.

parseJavaClassPathback to summary
pack-priv static ImmutableList<URL> parseJavaClassPath()

Returns the URLs in the class path specified by the java.class.path system property.

Annotations
@VisibleForTesting
toFileback to summary
pack-priv static File toFile(URL url)
Annotations
@VisibleForTesting
com.google.common.reflect back to summary

public final Class ClassPath.ClassInfo

extends ResourceInfo
Class Inheritance

Represents a class that can be loaded through load.
Since
14.0

Field Summary

Modifier and TypeField and Description
private final String
Inherited from com.google.common.reflect.ClassPath.ResourceInfo:
loader

Constructor Summary

AccessConstructor and Description
pack-priv
ClassInfo(File file, String resourceName, ClassLoader loader)

Method Summary

Modifier and TypeMethod and Description
public String
getName()

Returns the fully qualified name of the class.

public String
getPackageName()

Returns the package name of the class, without attempting to load the class.

public String
getSimpleName()

Returns the simple name of the underlying class as given in the source code.

public boolean
isTopLevel()

Returns true if the class name "looks to be" top level (not nested), that is, it includes no '$' in the name.

public Class<?>
load()

Loads (but doesn't link or initialize) the class.

public String
toString()

Overrides com.google.common.reflect.ClassPath.ResourceInfo.toString.

Returns a string representation of the object.
Inherited from com.google.common.reflect.ClassPath.ResourceInfo:
asByteSourceasCharSourceequalsgetFilegetResourceNamehashCodeofurl

Field Detail

classNameback to summary
private final String className

Constructor Detail

ClassInfoback to summary
pack-priv ClassInfo(File file, String resourceName, ClassLoader loader)

Method Detail

getNameback to summary
public String getName()

Returns the fully qualified name of the class.

Behaves identically to Class#getName() but does not require the class to be loaded.

getPackageNameback to summary
public String getPackageName()

Returns the package name of the class, without attempting to load the class.

Behaves similarly to class.getPackage().getName() but does not require the class (or package) to be loaded.

But note that this method may behave differently for a class in the default package: For such classes, this method always returns an empty string. But under some version of Java, class.getPackage().getName() produces a NullPointerException because class.getPackage() returns null.

getSimpleNameback to summary
public String getSimpleName()

Returns the simple name of the underlying class as given in the source code.

Behaves similarly to Class#getSimpleName() but does not require the class to be loaded.

But note that this class uses heuristics to identify the simple name. See a related discussion in issue 3349.

isTopLevelback to summary
public boolean isTopLevel()

Returns true if the class name "looks to be" top level (not nested), that is, it includes no '$' in the name. This method may return false for a top-level class that's intentionally named with the '$' character. If this is a concern, you could use load and then check on the loaded Class object instead.

Since
30.1
loadback to summary
public Class<?> load()

Loads (but doesn't link or initialize) the class.

Exceptions
LinkageError:
when there were errors in loading classes that this class depends on. For example, NoClassDefFoundError.
toStringback to summary
public String toString()

Overrides com.google.common.reflect.ClassPath.ResourceInfo.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object.

Returns:String

a string representation of the object

Annotations
@Override
com.google.common.reflect back to summary

pack-priv final Class ClassPath.LocationInfo

extends Object
Class Inheritance

Represents a single location (a directory or a jar file) in the class path and is responsible for scanning resources from this location.

Field Summary

Modifier and TypeField and Description
private final ClassLoader
pack-priv final File

Constructor Summary

AccessConstructor and Description
pack-priv
LocationInfo(File home, ClassLoader classloader)

Method Summary

Modifier and TypeMethod and Description
public boolean
equals(Object
the reference object with which to compare.
obj
)

Overrides java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.
public final File
file()

Returns the file this location is from.

public int
hashCode()

Overrides java.lang.Object.hashCode.

Returns a hash code value for this object.
private void
scan(File file, Set<File> scannedUris, ImmutableSet.Builder<ClassPath.ResourceInfo> builder)

private void
private void
scanDirectory(File
the root of the directory to scan
directory
,
String
resource path prefix inside classloader for any files found under directory
packagePrefix
,
Set<File>
canonical files already visited in the current directory tree path, for cycle elimination
currentPath
,
ImmutableSet.Builder<ClassPath.ResourceInfo> builder)

Recursively scan the given directory, adding resources for each file encountered.

private void
private void
public ImmutableSet<ClassPath.ResourceInfo>
scanResources()

Scans this location and returns all scanned resources.

public ImmutableSet<ClassPath.ResourceInfo>
scanResources(Set<File> scannedFiles)

Scans this location and returns all scanned resources.

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.
Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAllwaitwaitwait

Field Detail

classloaderback to summary
private final ClassLoader classloader
homeback to summary
pack-priv final File home

Constructor Detail

LocationInfoback to summary
pack-priv LocationInfo(File home, ClassLoader classloader)

Method Detail

equalsback to summary
public boolean equals(Object obj)

Overrides java.lang.Object.equals.

Doc from java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

An equivalence relation partitions the elements it operates on into equivalence classes; all the members of an equivalence class are equal to each other. Members of an equivalence class are substitutable for each other, at least for some purposes.

Parameters
obj:Object

the reference object with which to compare.

Returns:boolean

true if this object is the same as the obj argument; false otherwise.

Annotations
@Override
fileback to summary
public final File file()

Returns the file this location is from.

hashCodeback to summary
public int hashCode()

Overrides java.lang.Object.hashCode.

Doc from java.lang.Object.hashCode.

Returns a hash code value for this object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Returns:int

a hash code value for this object

Annotations
@Override
scanback to summary
private void scan(File file, Set<File> scannedUris, ImmutableSet.Builder<ClassPath.ResourceInfo> builder) throws IOException
scanDirectoryback to summary
private void scanDirectory(File directory, ImmutableSet.Builder<ClassPath.ResourceInfo> builder) throws IOException
scanDirectoryback to summary
private void scanDirectory(File directory, String packagePrefix, Set<File> currentPath, ImmutableSet.Builder<ClassPath.ResourceInfo> builder) throws IOException

Recursively scan the given directory, adding resources for each file encountered. Symlinks which have already been traversed in the current tree path will be skipped to eliminate cycles; otherwise symlinks are traversed.

Parameters
directory:File

the root of the directory to scan

packagePrefix:String

resource path prefix inside classloader for any files found under directory

currentPath:Set<File>

canonical files already visited in the current directory tree path, for cycle elimination

scanJarback to summary
private void scanJar(File file, Set<File> scannedUris, ImmutableSet.Builder<ClassPath.ResourceInfo> builder) throws IOException
scanJarFileback to summary
private void scanJarFile(JarFile file, ImmutableSet.Builder<ClassPath.ResourceInfo> builder)
scanResourcesback to summary
public ImmutableSet<ClassPath.ResourceInfo> scanResources() throws IOException

Scans this location and returns all scanned resources.

scanResourcesback to summary
public ImmutableSet<ClassPath.ResourceInfo> scanResources(Set<File> scannedFiles) throws IOException

Scans this location and returns all scanned resources.

This file and jar files from "Class-Path" entry in the scanned manifest files will be added to scannedFiles.

A file will be scanned at most once even if specified multiple times by one or multiple jar files' "Class-Path" manifest entries. Particularly, if a jar file from the "Class-Path" manifest entry is already in scannedFiles, either because it was scanned earlier, or it was intentionally added to the set by the caller, it will not be scanned again.

Note that when you call location.scanResources(scannedFiles), the location will always be scanned even if scannedFiles already contains it.

toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object.

Returns:String

a string representation of the object

Annotations
@Override
com.google.common.reflect back to summary

public Class ClassPath.ResourceInfo

extends Object
Class Inheritance
Known Direct Subclasses
com.google.common.reflect.ClassPath.ClassInfo

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

Field Summary

Modifier and TypeField and Description
private final File
pack-priv final ClassLoader
private final String

Constructor Summary

AccessConstructor and Description
pack-priv
ResourceInfo(File file, String resourceName, ClassLoader loader)

Method Summary

Modifier and TypeMethod and Description
public final ByteSource
asByteSource()

Returns a ByteSource view of the resource from which its bytes can be read.

public final CharSource
asCharSource(Charset charset)

Returns a CharSource view of the resource from which its bytes can be read as characters decoded with the given charset.

public boolean
equals(Object
the reference object with which to compare.
obj
)

Overrides java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.
pack-priv final File
getFile()

Returns the file that includes this resource.

public final String
getResourceName()

Returns the fully qualified name of the resource.

public int
hashCode()

Overrides java.lang.Object.hashCode.

Returns a hash code value for this object.
pack-priv static ClassPath.ResourceInfo
of(File file, String resourceName, ClassLoader loader)

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.
public final URL
url()

Returns the url identifying the resource.

Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAllwaitwaitwait

Field Detail

fileback to summary
private final File file
loaderback to summary
pack-priv final ClassLoader loader
resourceNameback to summary
private final String resourceName

Constructor Detail

ResourceInfoback to summary
pack-priv ResourceInfo(File file, String resourceName, ClassLoader loader)

Method Detail

asByteSourceback to summary
public final ByteSource asByteSource()

Returns a ByteSource view of the resource from which its bytes can be read.

Exceptions
NoSuchElementException:
if the resource cannot be loaded through the class loader, despite physically existing in the class path.
Since
20.0
asCharSourceback to summary
public final CharSource asCharSource(Charset charset)

Returns a CharSource view of the resource from which its bytes can be read as characters decoded with the given charset.

Exceptions
NoSuchElementException:
if the resource cannot be loaded through the class loader, despite physically existing in the class path.
Since
20.0
equalsback to summary
public boolean equals(Object obj)

Overrides java.lang.Object.equals.

Doc from java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

An equivalence relation partitions the elements it operates on into equivalence classes; all the members of an equivalence class are equal to each other. Members of an equivalence class are substitutable for each other, at least for some purposes.

Parameters
obj:Object

the reference object with which to compare.

Returns:boolean

true if this object is the same as the obj argument; false otherwise.

Annotations
@Override
getFileback to summary
pack-priv final File getFile()

Returns the file that includes this resource.

getResourceNameback to summary
public final String getResourceName()

Returns the fully qualified name of the resource. Such as "com/mycomp/foo/bar.txt".

hashCodeback to summary
public int hashCode()

Overrides java.lang.Object.hashCode.

Doc from java.lang.Object.hashCode.

Returns a hash code value for this object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Returns:int

a hash code value for this object

Annotations
@Override
ofback to summary
pack-priv static ClassPath.ResourceInfo of(File file, String resourceName, ClassLoader loader)
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object.

Returns:String

a string representation of the object

Annotations
@Override
urlback to summary
public final URL url()

Returns the url identifying the resource.

See ClassLoader#getResource

Exceptions
NoSuchElementException:
if the resource cannot be loaded through the class loader, despite physically existing in the class path.