Java runtime metadata analysis library that enables reverse querying of classpath metadata for type system introspection
—
Extensive utility classes for classpath operations, filtering, name resolution, and reflection operations to support the core scanning functionality. These utilities provide essential helper functions for working with classpaths, URLs, and Java reflection.
Helper methods for working with classpath URLs and class loaders.
/**
* Helper methods for working with classpath
*/
abstract class ClasspathHelper {
/** Get current thread context class loader */
static ClassLoader contextClassLoader();
/** Get Reflections library class loader */
static ClassLoader staticClassLoader();
/** Get array of class loaders with fallbacks */
static ClassLoader[] classLoaders(ClassLoader... classLoaders);
/** Get URLs for package prefix */
static Collection<URL> forPackage(String name, ClassLoader... classLoaders);
/** Get URLs for resource name */
static Collection<URL> forResource(String resourceName, ClassLoader... classLoaders);
/** Get URL containing specific class */
static URL forClass(Class<?> aClass, ClassLoader... classLoaders);
/** Get URLs from default class loaders */
static Collection<URL> forClassLoader();
/** Get URLs from specific class loaders */
static Collection<URL> forClassLoader(ClassLoader... classLoaders);
/** Get URLs from java.class.path system property */
static Collection<URL> forJavaClassPath();
/** Get URLs from WEB-INF/lib directory in servlet context */
static Collection<URL> forWebInfLib(ServletContext servletContext);
/** Get URL for WEB-INF/classes directory in servlet context */
static URL forWebInfClasses(ServletContext servletContext);
/** Get URLs with manifest Class-Path expansion */
static Collection<URL> forManifest();
/** Expand single URL with manifest Class-Path entries */
static Collection<URL> forManifest(URL url);
/** Expand URLs with manifest Class-Path entries */
static Collection<URL> forManifest(Iterable<URL> urls);
/** Clean URL path for consistent formatting */
static String cleanPath(URL url);
}Builder class for creating include/exclude filters to control what gets scanned.
/**
* Builder for include/exclude filters
*/
class FilterBuilder implements Predicate<String> {
/** Default constructor */
FilterBuilder();
/** Parse include/exclude packages from CSV string */
static FilterBuilder parsePackages(String includeExcludeString);
/** Include package prefix */
FilterBuilder includePackage(String value);
/** Exclude package prefix */
FilterBuilder excludePackage(String value);
/** Include regex pattern */
FilterBuilder includePattern(String regex);
/** Exclude regex pattern */
FilterBuilder excludePattern(String regex);
/** @Deprecated Include regex (use includePattern) */
@Deprecated FilterBuilder include(String regex);
/** @Deprecated Exclude regex (use excludePattern) */
@Deprecated FilterBuilder exclude(String regex);
/** Add custom predicate filter */
FilterBuilder add(Predicate<String> filter);
/** Test string against all configured filters */
boolean test(String regex);
}Helper interface for converting between reflection elements and their string names.
/**
* Helper for converting between elements and names
*/
interface NameHelper {
/** Primitive type names list */
List<String> primitiveNames = Arrays.asList("boolean", "char", "byte", "short", "int", "long", "float", "double");
/** Primitive type classes list */
List<Class<?>> primitiveTypes = Arrays.asList(boolean.class, char.class, byte.class, short.class, int.class, long.class, float.class, double.class);
/** Primitive type descriptors list */
List<String> primitiveDescriptors = Arrays.asList("Z", "C", "B", "S", "I", "J", "F", "D");
/** Convert annotated element to name string */
default String toName(AnnotatedElement element);
/** Convert class to name string */
default String toName(Class<?> type);
/** Convert constructor to name string */
default String toName(Constructor<?> constructor);
/** Convert method to name string */
default String toName(Method method);
/** Convert field to name string */
default String toName(Field field);
/** Convert collection of elements to names */
default Collection<String> toNames(Collection<? extends AnnotatedElement> elements);
/** Convert varargs elements to names */
default Collection<String> toNames(AnnotatedElement... elements);
/** Resolve name string to typed element */
default <T> T forName(String name, Class<T> resultType, ClassLoader... loaders);
/** Resolve type name to Class */
default Class<?> forClass(String typeName, ClassLoader... loaders);
/** Resolve descriptor to Member */
default Member forMember(String descriptor, ClassLoader... loaders);
/** Resolve descriptor to Method */
default Method forMethod(String descriptor, ClassLoader... loaders);
/** Resolve descriptor to Constructor */
default Constructor<?> forConstructor(String descriptor, ClassLoader... loaders);
/** Resolve descriptor to Field */
default Field forField(String descriptor, ClassLoader... loaders);
/** Resolve collection of names to typed elements */
default <T> Collection<T> forNames(Collection<String> names, Class<T> resultType, ClassLoader... loaders);
/** Resolve collection of names to Classes */
default Collection<Class<?>> forNames(Collection<String> names, ClassLoader... loaders);
}Builder interface for creating store queries with transitive and syntactic sugar methods.
/**
* Builder interface for store queries
*/
interface QueryBuilder extends NameHelper {
/** Get scanner index name */
default String index();
/** Get values for specific key */
default QueryFunction<Store, String> get(String key);
/** Get values for annotated element */
default QueryFunction<Store, String> get(AnnotatedElement element);
/** Get values for collection of keys */
default QueryFunction<Store, String> get(Collection<String> keys);
/** Get transitive values for keys */
default QueryFunction<Store, String> getAll(Collection<String> keys);
/** Get transitive values including specific key */
default QueryFunction<Store, String> getAllIncluding(String key);
/** Get transitive values including collection of keys */
default QueryFunction<Store, String> getAllIncluding(Collection<String> keys);
/** Alias for getAll(Collection) */
default QueryFunction<Store, String> of(Collection<String> keys);
/** Alias for getAll with single key */
default QueryFunction<Store, String> of(String key);
/** Get transitive values for annotated elements */
default QueryFunction<Store, String> of(AnnotatedElement... elements);
/** Get transitive values for set of annotated elements */
default QueryFunction<Store, String> of(Set<? extends AnnotatedElement> elements);
/** Various "with" aliases for "of" methods */
default QueryFunction<Store, String> with(String key);
default QueryFunction<Store, String> with(String... keys);
default QueryFunction<Store, String> with(AnnotatedElement... elements);
default QueryFunction<Store, String> with(Collection<String> keys);
default QueryFunction<Store, String> with(Set<? extends AnnotatedElement> elements);
/** Compose with another query function */
default <T> QueryFunction<Store, T> of(QueryFunction queryFunction);
}Additional utility classes providing specialized functionality.
/**
* Query builder for ReflectionUtils operations
*/
class UtilQueryBuilder<C, T> implements QueryBuilder {
// Implementation for ReflectionUtils query building
}
/**
* Predicates for reflection filtering operations
*/
abstract class ReflectionUtilsPredicates {
// Common predicates for filtering reflection results
}
/**
* Helper for Javassist bytecode operations
*/
abstract class JavassistHelper {
// Utility methods for working with Javassist ClassFile objects
}
/**
* Collector for merging annotations
*/
class AnnotationMergeCollector {
// Implementation for collecting and merging annotation data
}import org.reflections.util.ClasspathHelper;
import java.net.URL;
import java.util.Collection;
// Get URLs for packages
Collection<URL> urls = ClasspathHelper.forPackage("com.mycompany");
Collection<URL> multiplePackages = ClasspathHelper.forPackage("com.mycompany",
MyClass.class.getClassLoader());
// Get URLs for resources
Collection<URL> configUrls = ClasspathHelper.forResource("application.properties");
// Get URLs from various sources
Collection<URL> classpathUrls = ClasspathHelper.forJavaClassPath();
Collection<URL> classLoaderUrls = ClasspathHelper.forClassLoader();
Collection<URL> specificClassLoaderUrls = ClasspathHelper.forClassLoader(
Thread.currentThread().getContextClassLoader());
// Get URL for specific class
URL classUrl = ClasspathHelper.forClass(String.class);
// Work with class loaders
ClassLoader contextCL = ClasspathHelper.contextClassLoader();
ClassLoader staticCL = ClasspathHelper.staticClassLoader();
ClassLoader[] allLoaders = ClasspathHelper.classLoaders(contextCL, staticCL);import org.reflections.util.FilterBuilder;
// Package-based filtering
FilterBuilder filter = new FilterBuilder()
.includePackage("com.mycompany")
.includePackage("org.springframework")
.excludePackage("com.mycompany.test")
.excludePackage("com.mycompany.internal");
// Pattern-based filtering
FilterBuilder patternFilter = new FilterBuilder()
.includePattern(".*Service.*")
.includePattern(".*Repository.*")
.includePattern(".*Controller.*")
.excludePattern(".*Test.*")
.excludePattern(".*Mock.*");
// Parse from string
FilterBuilder parsed = FilterBuilder.parsePackages(
"com.mycompany,-com.mycompany.test,org.springframework");
// Custom predicate filtering
FilterBuilder customFilter = new FilterBuilder()
.add(className -> className.length() > 10)
.add(className -> !className.contains("$")) // exclude inner classes
.includePackage("com.mycompany");
// Test filters
boolean matches = filter.test("com.mycompany.service.UserService"); // true
boolean excluded = filter.test("com.mycompany.test.UserServiceTest"); // falseimport org.reflections.util.NameHelper;
// Convert elements to names
class MyClass implements NameHelper {
public void example() {
// Convert class to name
String className = toName(String.class); // "java.lang.String"
// Convert method to name
Method method = String.class.getMethod("substring", int.class);
String methodName = toName(method); // "java.lang.String.substring(int)"
// Convert field to name
Field field = MyClass.class.getDeclaredField("myField");
String fieldName = toName(field); // "com.example.MyClass.myField"
// Convert constructor to name
Constructor<?> constructor = String.class.getConstructor(String.class);
String constructorName = toName(constructor); // "java.lang.String.<init>(java.lang.String)"
// Convert collections
Collection<String> names = toNames(String.class.getMethods());
// Resolve names back to elements
Class<?> resolvedClass = forClass("java.lang.String");
Method resolvedMethod = forMethod("java.lang.String.substring(int)");
Field resolvedField = forField("com.example.MyClass.myField");
// Resolve collections
Collection<Class<?>> classes = forNames(Arrays.asList("java.lang.String", "java.lang.Integer"));
}
}import org.reflections.scanners.Scanners;
import org.reflections.util.QueryFunction;
import static org.reflections.scanners.Scanners.*;
// Basic queries
QueryFunction<Store, String> subtypes = SubTypes.get(MyInterface.class);
QueryFunction<Store, String> annotated = TypesAnnotated.get(MyAnnotation.class);
// Transitive queries
QueryFunction<Store, String> allSubtypes = SubTypes.getAll(Arrays.asList("com.example.Interface1", "com.example.Interface2"));
QueryFunction<Store, String> transitiveAnnotated = TypesAnnotated.getAllIncluding("com.example.BaseClass");
// Syntactic sugar methods
QueryFunction<Store, String> query1 = SubTypes.of("com.example.MyInterface");
QueryFunction<Store, String> query2 = MethodsAnnotated.with(Override.class);
QueryFunction<Store, String> query3 = Resources.with(".*\\.xml");
// Convert to typed results
QueryFunction<Store, Class<?>> typedQuery = SubTypes.of(MyInterface.class).asClass();
QueryFunction<Store, Method> methodQuery = MethodsAnnotated.with(MyAnnotation.class).as(Method.class);// Complex filtering scenario
FilterBuilder complexFilter = new FilterBuilder()
// Include main application packages
.includePackage("com.mycompany.api")
.includePackage("com.mycompany.service")
.includePackage("com.mycompany.repository")
// Exclude test and internal packages
.excludePackage("com.mycompany.test")
.excludePackage("com.mycompany.internal")
// Include specific Spring annotations
.includePattern(".*@.*Service.*")
.includePattern(".*@.*Controller.*")
.includePattern(".*@.*Repository.*")
// Exclude generated and proxy classes
.excludePattern(".*\\$\\$.*") // CGLib proxies
.excludePattern(".*\\$Proxy.*") // JDK proxies
.excludePattern(".*_\\$\\$_.*") // Mockito mocks
// Custom business logic filters
.add(className -> !className.contains("Generated"))
.add(className -> className.length() < 100); // reasonable class name length
// Use in configuration
ConfigurationBuilder config = new ConfigurationBuilder()
.forPackages("com.mycompany")
.filterInputsBy(complexFilter);// Comprehensive URL discovery
Collection<URL> allUrls = new HashSet<>();
// Add package-specific URLs
allUrls.addAll(ClasspathHelper.forPackage("com.mycompany"));
// Add classpath URLs
allUrls.addAll(ClasspathHelper.forJavaClassPath());
// Add class loader URLs
allUrls.addAll(ClasspathHelper.forClassLoader(
Thread.currentThread().getContextClassLoader(),
MyClass.class.getClassLoader()));
// Add manifest URLs for additional class path entries
allUrls = ClasspathHelper.forManifest(allUrls);
// Use in configuration
ConfigurationBuilder config = new ConfigurationBuilder()
.setUrls(allUrls)
.filterInputsBy(new FilterBuilder().includePackage("com.mycompany"));public class FilterStrategy {
public static FilterBuilder createProductionFilter() {
return new FilterBuilder()
.includePackage("com.mycompany")
.excludePackage("com.mycompany.test")
.excludePattern(".*Mock.*")
.excludePattern(".*Test.*");
}
public static FilterBuilder createDevelopmentFilter() {
return new FilterBuilder()
.includePackage("com.mycompany")
.includePattern(".*Test.*"); // include tests in dev
}
public static FilterBuilder createMinimalFilter() {
return new FilterBuilder()
.includePattern(".*Service.*")
.includePattern(".*Repository.*")
.excludePattern(".*Test.*");
}
}Additional utility methods for working with annotations, maps, and reflection operations.
/**
* Utility methods for annotation and reflection operations
*/
abstract class ReflectionUtils {
/** Convert annotation to key-value map */
static Map<String, Object> toMap(Annotation annotation);
/** Convert annotation to map with context element */
static Map<String, Object> toMap(Annotation annotation, AnnotatedElement element);
/** Convert map to annotation instance */
static Annotation toAnnotation(Map<String, Object> map);
/** Convert map to typed annotation instance */
static <T extends Annotation> T toAnnotation(Map<String, Object> map, Class<T> annotationType);
/** Safely invoke method with error handling */
static Object invoke(Method method, Object obj, Object... args);
}import org.reflections.ReflectionUtils;
import java.lang.annotation.Annotation;
import java.util.Map;
// Convert annotation to map
@MyAnnotation(value = "test", count = 42)
class MyClass {}
Annotation annotation = MyClass.class.getAnnotation(MyAnnotation.class);
Map<String, Object> annotationMap = ReflectionUtils.toMap(annotation);
// Result: {"value": "test", "count": 42}
// Convert map back to annotation
MyAnnotation reconstructed = ReflectionUtils.toAnnotation(annotationMap, MyAnnotation.class);
// Safely invoke methods
Method method = MyClass.class.getMethod("someMethod");
Object result = ReflectionUtils.invoke(method, myClassInstance);/**
* Exception thrown by utility operations
*/
class ReflectionsException extends RuntimeException {
ReflectionsException(String message);
ReflectionsException(String message, Throwable cause);
ReflectionsException(Throwable cause);
}Install with Tessl CLI
npx tessl i tessl/maven-org-reflections--reflections