0
# Utilities
1
2
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.
3
4
## Capabilities
5
6
### ClasspathHelper
7
8
Helper methods for working with classpath URLs and class loaders.
9
10
```java { .api }
11
/**
12
* Helper methods for working with classpath
13
*/
14
abstract class ClasspathHelper {
15
/** Get current thread context class loader */
16
static ClassLoader contextClassLoader();
17
18
/** Get Reflections library class loader */
19
static ClassLoader staticClassLoader();
20
21
/** Get array of class loaders with fallbacks */
22
static ClassLoader[] classLoaders(ClassLoader... classLoaders);
23
24
/** Get URLs for package prefix */
25
static Collection<URL> forPackage(String name, ClassLoader... classLoaders);
26
27
/** Get URLs for resource name */
28
static Collection<URL> forResource(String resourceName, ClassLoader... classLoaders);
29
30
/** Get URL containing specific class */
31
static URL forClass(Class<?> aClass, ClassLoader... classLoaders);
32
33
/** Get URLs from default class loaders */
34
static Collection<URL> forClassLoader();
35
36
/** Get URLs from specific class loaders */
37
static Collection<URL> forClassLoader(ClassLoader... classLoaders);
38
39
/** Get URLs from java.class.path system property */
40
static Collection<URL> forJavaClassPath();
41
42
/** Get URLs from WEB-INF/lib directory in servlet context */
43
static Collection<URL> forWebInfLib(ServletContext servletContext);
44
45
/** Get URL for WEB-INF/classes directory in servlet context */
46
static URL forWebInfClasses(ServletContext servletContext);
47
48
/** Get URLs with manifest Class-Path expansion */
49
static Collection<URL> forManifest();
50
51
/** Expand single URL with manifest Class-Path entries */
52
static Collection<URL> forManifest(URL url);
53
54
/** Expand URLs with manifest Class-Path entries */
55
static Collection<URL> forManifest(Iterable<URL> urls);
56
57
/** Clean URL path for consistent formatting */
58
static String cleanPath(URL url);
59
}
60
```
61
62
### FilterBuilder
63
64
Builder class for creating include/exclude filters to control what gets scanned.
65
66
```java { .api }
67
/**
68
* Builder for include/exclude filters
69
*/
70
class FilterBuilder implements Predicate<String> {
71
/** Default constructor */
72
FilterBuilder();
73
74
/** Parse include/exclude packages from CSV string */
75
static FilterBuilder parsePackages(String includeExcludeString);
76
77
/** Include package prefix */
78
FilterBuilder includePackage(String value);
79
80
/** Exclude package prefix */
81
FilterBuilder excludePackage(String value);
82
83
/** Include regex pattern */
84
FilterBuilder includePattern(String regex);
85
86
/** Exclude regex pattern */
87
FilterBuilder excludePattern(String regex);
88
89
/** @Deprecated Include regex (use includePattern) */
90
@Deprecated FilterBuilder include(String regex);
91
92
/** @Deprecated Exclude regex (use excludePattern) */
93
@Deprecated FilterBuilder exclude(String regex);
94
95
/** Add custom predicate filter */
96
FilterBuilder add(Predicate<String> filter);
97
98
/** Test string against all configured filters */
99
boolean test(String regex);
100
}
101
```
102
103
### NameHelper Interface
104
105
Helper interface for converting between reflection elements and their string names.
106
107
```java { .api }
108
/**
109
* Helper for converting between elements and names
110
*/
111
interface NameHelper {
112
/** Primitive type names list */
113
List<String> primitiveNames = Arrays.asList("boolean", "char", "byte", "short", "int", "long", "float", "double");
114
115
/** Primitive type classes list */
116
List<Class<?>> primitiveTypes = Arrays.asList(boolean.class, char.class, byte.class, short.class, int.class, long.class, float.class, double.class);
117
118
/** Primitive type descriptors list */
119
List<String> primitiveDescriptors = Arrays.asList("Z", "C", "B", "S", "I", "J", "F", "D");
120
121
/** Convert annotated element to name string */
122
default String toName(AnnotatedElement element);
123
124
/** Convert class to name string */
125
default String toName(Class<?> type);
126
127
/** Convert constructor to name string */
128
default String toName(Constructor<?> constructor);
129
130
/** Convert method to name string */
131
default String toName(Method method);
132
133
/** Convert field to name string */
134
default String toName(Field field);
135
136
/** Convert collection of elements to names */
137
default Collection<String> toNames(Collection<? extends AnnotatedElement> elements);
138
139
/** Convert varargs elements to names */
140
default Collection<String> toNames(AnnotatedElement... elements);
141
142
/** Resolve name string to typed element */
143
default <T> T forName(String name, Class<T> resultType, ClassLoader... loaders);
144
145
/** Resolve type name to Class */
146
default Class<?> forClass(String typeName, ClassLoader... loaders);
147
148
/** Resolve descriptor to Member */
149
default Member forMember(String descriptor, ClassLoader... loaders);
150
151
/** Resolve descriptor to Method */
152
default Method forMethod(String descriptor, ClassLoader... loaders);
153
154
/** Resolve descriptor to Constructor */
155
default Constructor<?> forConstructor(String descriptor, ClassLoader... loaders);
156
157
/** Resolve descriptor to Field */
158
default Field forField(String descriptor, ClassLoader... loaders);
159
160
/** Resolve collection of names to typed elements */
161
default <T> Collection<T> forNames(Collection<String> names, Class<T> resultType, ClassLoader... loaders);
162
163
/** Resolve collection of names to Classes */
164
default Collection<Class<?>> forNames(Collection<String> names, ClassLoader... loaders);
165
}
166
```
167
168
### QueryBuilder Interface
169
170
Builder interface for creating store queries with transitive and syntactic sugar methods.
171
172
```java { .api }
173
/**
174
* Builder interface for store queries
175
*/
176
interface QueryBuilder extends NameHelper {
177
/** Get scanner index name */
178
default String index();
179
180
/** Get values for specific key */
181
default QueryFunction<Store, String> get(String key);
182
183
/** Get values for annotated element */
184
default QueryFunction<Store, String> get(AnnotatedElement element);
185
186
/** Get values for collection of keys */
187
default QueryFunction<Store, String> get(Collection<String> keys);
188
189
/** Get transitive values for keys */
190
default QueryFunction<Store, String> getAll(Collection<String> keys);
191
192
/** Get transitive values including specific key */
193
default QueryFunction<Store, String> getAllIncluding(String key);
194
195
/** Get transitive values including collection of keys */
196
default QueryFunction<Store, String> getAllIncluding(Collection<String> keys);
197
198
/** Alias for getAll(Collection) */
199
default QueryFunction<Store, String> of(Collection<String> keys);
200
201
/** Alias for getAll with single key */
202
default QueryFunction<Store, String> of(String key);
203
204
/** Get transitive values for annotated elements */
205
default QueryFunction<Store, String> of(AnnotatedElement... elements);
206
207
/** Get transitive values for set of annotated elements */
208
default QueryFunction<Store, String> of(Set<? extends AnnotatedElement> elements);
209
210
/** Various "with" aliases for "of" methods */
211
default QueryFunction<Store, String> with(String key);
212
default QueryFunction<Store, String> with(String... keys);
213
default QueryFunction<Store, String> with(AnnotatedElement... elements);
214
default QueryFunction<Store, String> with(Collection<String> keys);
215
default QueryFunction<Store, String> with(Set<? extends AnnotatedElement> elements);
216
217
/** Compose with another query function */
218
default <T> QueryFunction<Store, T> of(QueryFunction queryFunction);
219
}
220
```
221
222
### Other Utility Classes
223
224
Additional utility classes providing specialized functionality.
225
226
```java { .api }
227
/**
228
* Query builder for ReflectionUtils operations
229
*/
230
class UtilQueryBuilder<C, T> implements QueryBuilder {
231
// Implementation for ReflectionUtils query building
232
}
233
234
/**
235
* Predicates for reflection filtering operations
236
*/
237
abstract class ReflectionUtilsPredicates {
238
// Common predicates for filtering reflection results
239
}
240
241
/**
242
* Helper for Javassist bytecode operations
243
*/
244
abstract class JavassistHelper {
245
// Utility methods for working with Javassist ClassFile objects
246
}
247
248
/**
249
* Collector for merging annotations
250
*/
251
class AnnotationMergeCollector {
252
// Implementation for collecting and merging annotation data
253
}
254
```
255
256
## Usage Examples
257
258
### ClasspathHelper Usage
259
260
```java
261
import org.reflections.util.ClasspathHelper;
262
import java.net.URL;
263
import java.util.Collection;
264
265
// Get URLs for packages
266
Collection<URL> urls = ClasspathHelper.forPackage("com.mycompany");
267
Collection<URL> multiplePackages = ClasspathHelper.forPackage("com.mycompany",
268
MyClass.class.getClassLoader());
269
270
// Get URLs for resources
271
Collection<URL> configUrls = ClasspathHelper.forResource("application.properties");
272
273
// Get URLs from various sources
274
Collection<URL> classpathUrls = ClasspathHelper.forJavaClassPath();
275
Collection<URL> classLoaderUrls = ClasspathHelper.forClassLoader();
276
Collection<URL> specificClassLoaderUrls = ClasspathHelper.forClassLoader(
277
Thread.currentThread().getContextClassLoader());
278
279
// Get URL for specific class
280
URL classUrl = ClasspathHelper.forClass(String.class);
281
282
// Work with class loaders
283
ClassLoader contextCL = ClasspathHelper.contextClassLoader();
284
ClassLoader staticCL = ClasspathHelper.staticClassLoader();
285
ClassLoader[] allLoaders = ClasspathHelper.classLoaders(contextCL, staticCL);
286
```
287
288
### FilterBuilder Usage
289
290
```java
291
import org.reflections.util.FilterBuilder;
292
293
// Package-based filtering
294
FilterBuilder filter = new FilterBuilder()
295
.includePackage("com.mycompany")
296
.includePackage("org.springframework")
297
.excludePackage("com.mycompany.test")
298
.excludePackage("com.mycompany.internal");
299
300
// Pattern-based filtering
301
FilterBuilder patternFilter = new FilterBuilder()
302
.includePattern(".*Service.*")
303
.includePattern(".*Repository.*")
304
.includePattern(".*Controller.*")
305
.excludePattern(".*Test.*")
306
.excludePattern(".*Mock.*");
307
308
// Parse from string
309
FilterBuilder parsed = FilterBuilder.parsePackages(
310
"com.mycompany,-com.mycompany.test,org.springframework");
311
312
// Custom predicate filtering
313
FilterBuilder customFilter = new FilterBuilder()
314
.add(className -> className.length() > 10)
315
.add(className -> !className.contains("$")) // exclude inner classes
316
.includePackage("com.mycompany");
317
318
// Test filters
319
boolean matches = filter.test("com.mycompany.service.UserService"); // true
320
boolean excluded = filter.test("com.mycompany.test.UserServiceTest"); // false
321
```
322
323
### NameHelper Usage
324
325
```java
326
import org.reflections.util.NameHelper;
327
328
// Convert elements to names
329
class MyClass implements NameHelper {
330
public void example() {
331
// Convert class to name
332
String className = toName(String.class); // "java.lang.String"
333
334
// Convert method to name
335
Method method = String.class.getMethod("substring", int.class);
336
String methodName = toName(method); // "java.lang.String.substring(int)"
337
338
// Convert field to name
339
Field field = MyClass.class.getDeclaredField("myField");
340
String fieldName = toName(field); // "com.example.MyClass.myField"
341
342
// Convert constructor to name
343
Constructor<?> constructor = String.class.getConstructor(String.class);
344
String constructorName = toName(constructor); // "java.lang.String.<init>(java.lang.String)"
345
346
// Convert collections
347
Collection<String> names = toNames(String.class.getMethods());
348
349
// Resolve names back to elements
350
Class<?> resolvedClass = forClass("java.lang.String");
351
Method resolvedMethod = forMethod("java.lang.String.substring(int)");
352
Field resolvedField = forField("com.example.MyClass.myField");
353
354
// Resolve collections
355
Collection<Class<?>> classes = forNames(Arrays.asList("java.lang.String", "java.lang.Integer"));
356
}
357
}
358
```
359
360
### QueryBuilder Usage
361
362
```java
363
import org.reflections.scanners.Scanners;
364
import org.reflections.util.QueryFunction;
365
import static org.reflections.scanners.Scanners.*;
366
367
// Basic queries
368
QueryFunction<Store, String> subtypes = SubTypes.get(MyInterface.class);
369
QueryFunction<Store, String> annotated = TypesAnnotated.get(MyAnnotation.class);
370
371
// Transitive queries
372
QueryFunction<Store, String> allSubtypes = SubTypes.getAll(Arrays.asList("com.example.Interface1", "com.example.Interface2"));
373
QueryFunction<Store, String> transitiveAnnotated = TypesAnnotated.getAllIncluding("com.example.BaseClass");
374
375
// Syntactic sugar methods
376
QueryFunction<Store, String> query1 = SubTypes.of("com.example.MyInterface");
377
QueryFunction<Store, String> query2 = MethodsAnnotated.with(Override.class);
378
QueryFunction<Store, String> query3 = Resources.with(".*\\.xml");
379
380
// Convert to typed results
381
QueryFunction<Store, Class<?>> typedQuery = SubTypes.of(MyInterface.class).asClass();
382
QueryFunction<Store, Method> methodQuery = MethodsAnnotated.with(MyAnnotation.class).as(Method.class);
383
```
384
385
### Advanced Filter Combinations
386
387
```java
388
// Complex filtering scenario
389
FilterBuilder complexFilter = new FilterBuilder()
390
// Include main application packages
391
.includePackage("com.mycompany.api")
392
.includePackage("com.mycompany.service")
393
.includePackage("com.mycompany.repository")
394
395
// Exclude test and internal packages
396
.excludePackage("com.mycompany.test")
397
.excludePackage("com.mycompany.internal")
398
399
// Include specific Spring annotations
400
.includePattern(".*@.*Service.*")
401
.includePattern(".*@.*Controller.*")
402
.includePattern(".*@.*Repository.*")
403
404
// Exclude generated and proxy classes
405
.excludePattern(".*\\$\\$.*") // CGLib proxies
406
.excludePattern(".*\\$Proxy.*") // JDK proxies
407
.excludePattern(".*_\\$\\$_.*") // Mockito mocks
408
409
// Custom business logic filters
410
.add(className -> !className.contains("Generated"))
411
.add(className -> className.length() < 100); // reasonable class name length
412
413
// Use in configuration
414
ConfigurationBuilder config = new ConfigurationBuilder()
415
.forPackages("com.mycompany")
416
.filterInputsBy(complexFilter);
417
```
418
419
## Utility Integration Patterns
420
421
### URL Discovery Strategy
422
423
```java
424
// Comprehensive URL discovery
425
Collection<URL> allUrls = new HashSet<>();
426
427
// Add package-specific URLs
428
allUrls.addAll(ClasspathHelper.forPackage("com.mycompany"));
429
430
// Add classpath URLs
431
allUrls.addAll(ClasspathHelper.forJavaClassPath());
432
433
// Add class loader URLs
434
allUrls.addAll(ClasspathHelper.forClassLoader(
435
Thread.currentThread().getContextClassLoader(),
436
MyClass.class.getClassLoader()));
437
438
// Add manifest URLs for additional class path entries
439
allUrls = ClasspathHelper.forManifest(allUrls);
440
441
// Use in configuration
442
ConfigurationBuilder config = new ConfigurationBuilder()
443
.setUrls(allUrls)
444
.filterInputsBy(new FilterBuilder().includePackage("com.mycompany"));
445
```
446
447
### Filter Strategy Pattern
448
449
```java
450
public class FilterStrategy {
451
public static FilterBuilder createProductionFilter() {
452
return new FilterBuilder()
453
.includePackage("com.mycompany")
454
.excludePackage("com.mycompany.test")
455
.excludePattern(".*Mock.*")
456
.excludePattern(".*Test.*");
457
}
458
459
public static FilterBuilder createDevelopmentFilter() {
460
return new FilterBuilder()
461
.includePackage("com.mycompany")
462
.includePattern(".*Test.*"); // include tests in dev
463
}
464
465
public static FilterBuilder createMinimalFilter() {
466
return new FilterBuilder()
467
.includePattern(".*Service.*")
468
.includePattern(".*Repository.*")
469
.excludePattern(".*Test.*");
470
}
471
}
472
```
473
474
### ReflectionUtils Utility Methods
475
476
Additional utility methods for working with annotations, maps, and reflection operations.
477
478
```java { .api }
479
/**
480
* Utility methods for annotation and reflection operations
481
*/
482
abstract class ReflectionUtils {
483
/** Convert annotation to key-value map */
484
static Map<String, Object> toMap(Annotation annotation);
485
486
/** Convert annotation to map with context element */
487
static Map<String, Object> toMap(Annotation annotation, AnnotatedElement element);
488
489
/** Convert map to annotation instance */
490
static Annotation toAnnotation(Map<String, Object> map);
491
492
/** Convert map to typed annotation instance */
493
static <T extends Annotation> T toAnnotation(Map<String, Object> map, Class<T> annotationType);
494
495
/** Safely invoke method with error handling */
496
static Object invoke(Method method, Object obj, Object... args);
497
}
498
```
499
500
## Usage Examples
501
502
### Annotation Utilities
503
504
```java
505
import org.reflections.ReflectionUtils;
506
import java.lang.annotation.Annotation;
507
import java.util.Map;
508
509
// Convert annotation to map
510
@MyAnnotation(value = "test", count = 42)
511
class MyClass {}
512
513
Annotation annotation = MyClass.class.getAnnotation(MyAnnotation.class);
514
Map<String, Object> annotationMap = ReflectionUtils.toMap(annotation);
515
// Result: {"value": "test", "count": 42}
516
517
// Convert map back to annotation
518
MyAnnotation reconstructed = ReflectionUtils.toAnnotation(annotationMap, MyAnnotation.class);
519
520
// Safely invoke methods
521
Method method = MyClass.class.getMethod("someMethod");
522
Object result = ReflectionUtils.invoke(method, myClassInstance);
523
```
524
525
## Types
526
527
```java { .api }
528
/**
529
* Exception thrown by utility operations
530
*/
531
class ReflectionsException extends RuntimeException {
532
ReflectionsException(String message);
533
ReflectionsException(String message, Throwable cause);
534
ReflectionsException(Throwable cause);
535
}
536
```