Home

Awesome

❗ Please note: Reflections library is currently NOT under active development or maintenance ❗

Thank you for your continuous support! <br>There are open issues and also workarounds. Release version will be considered incase contributing PR fixing the main issues.

Last released org.reflections:reflections:0.10.2 (Oct 2021)


Java runtime metadata analysis

Build Status

Reflections scans and indexes your project's classpath metadata, allowing reverse transitive query of the type system on runtime.

Using Reflections you can query for example:

Reflections was written in the spirit of Scannotations library

Usage

Add Reflections dependency to your project:

# Maven
<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.10.2</version>
</dependency>

# Gradle
implementation 'org.reflections:reflections:0.10.2'

Create Reflections instance and use the query functions:

Reflections reflections = new Reflections("com.my.project");

Set<Class<?>> subTypes =
  reflections.get(SubTypes.of(SomeType.class).asClass());

Set<Class<?>> annotated = 
  reflections.get(SubTypes.of(TypesAnnotated.with(SomeAnnotation.class)).asClass());

Or using previous 0.9.x APIs, for example:

Set<Class<? extends SomeType>> subTypes =
  reflections.getSubTypesOf(SomeType.class);

Set<Class<?>> annotated = 
  reflections.getTypesAnnotatedWith(SomeAnnotation.class);

Note that there are some breaking changes with Reflections 0.10+, along with performance improvements and more functional API, see below.

Scan

Creating Reflections instance requires ConfigurationBuilder, typically configured with packages and Scanners to use:

// typical usage: scan package with the default scanners SubTypes, TypesAnnotated
Reflections reflections = new Reflections(
  new ConfigurationBuilder()
    .forPackage("com.my.project")
    .filterInputsBy(new FilterBuilder().includePackage("com.my.project")));

Other examples:

import static org.reflections.scanners.Scanners.*;

// scan package with specific scanners
Reflections reflections = new Reflections(
  new ConfigurationBuilder()
    .forPackage("com.my.project")
    .filterInputsBy(new FilterBuilder().includePackage("com.my.project").excludePackage("com.my.project.exclude"))
    .setScanners(TypesAnnotated, MethodsAnnotated, MethodsReturn));

Note that:

Query

Once Reflections was instantiated and scanning was successful, it can be used for querying the indexed metadata.

import static org.reflections.scanners.Scanners.*;

// SubTypes
Set<Class<?>> modules = 
  reflections.get(SubTypes.of(Module.class).asClass());

// TypesAnnotated (*1)
Set<Class<?>> singletons = 
  reflections.get(TypesAnnotated.with(Singleton.class).asClass());

// MethodsAnnotated
Set<Method> resources =
  reflections.get(MethodsAnnotated.with(GetMapping.class).as(Method.class));

// FieldsAnnotated
Set<Field> ids = 
  reflections.get(FieldsAnnotated.with(Id.class).as(Field.class));

// Resources
Set<String> properties = 
  reflections.get(Resources.with(".*\\.properties"));

More scanners:

// MethodsReturn
Set<Method> voidMethods = 
  reflections.get(MethodsReturn.with(void.class).as(Method.class));

// MethodsSignature
Set<Method> someMethods = 
  reflections.get(MethodsSignature.of(long.class, int.class).as(Method.class));

// MethodsParameter
Set<Method> pathParam = 
  reflections.get(MethodsParameter.of(PathParam.class).as(Method.class));

// ConstructorsAnnotated
Set<Constructor> injectables =
  reflections.get(ConstructorsAnnotated.with(Inject.class).as(Constructor.class));

// ConstructorsSignature
Set<Constructor> someConstructors = 
  reflections.get(ConstructorsSignature.of(String.class).as(Constructor.class));

// MethodParameterNamesScanner
List<String> parameterNames =
  reflections.getMemberParameterNames(member);

// MemberUsageScanner
Set<Member> usages =
  reflections.getMemberUsages(member)

See more examples in ReflectionsQueryTest.

Note that previous 0.9.x APIs are still supported

<details> <summary><i>Compare Scanners and previous 0.9.x API (*)</i></summary>
Scannersprevious 0.9.x APIprevious Scanner
get(SubType.of(T))getSubTypesOf(T)SubTypesScanner
get(SubTypes.of(<br>    TypesAnnotated.with(A)))getTypesAnnotatedWith(A) (1)TypeAnnotationsScanner
get(MethodsAnnotated.with(A))getMethodsAnnotatedWith(A)MethodAnnotationsScanner
get(ConstructorsAnnotated.with(A))getConstructorsAnnotatedWith(A) (2)MethodAnnotationsScanner
get(FieldsAnnotated.with(A))getFieldsAnnotatedWith(A)FieldAnnotationsScanner
get(Resources.with(regex))getResources(regex)ResourcesScanner
get(MethodsParameter.with(P))getMethodsWithParameter(P) (3)<br>getMethodsWithAnyParamAnnotated(P)MethodParameterScanner<br>obsolete
get(MethodsSignature.of(P, ...))getMethodsWithSignature(P, ...) (3)<br>getMethodsMatchParams(P, ...)"
get(MethodsReturn.of(T))getMethodsReturn(T) (3)"
get(ConstructorsParameter.with(P))getConstructorsWithParameter(P) (3)<br>getConstructorsWithAnyParamAnnotated(P)"
get(ConstructorsSignature.of(P, ...))getConstructorsWithSignature(P, ...) (3)<br>getConstructorsMatchParams(P, ...)"

Note: asClass() and as() mappings were omitted

(1): The equivalent of getTypesAnnotatedWith(A) is get(SubTypes.of(TypesAnnotated.with(A))), including SubTypes

(2): MethodsAnnotatedScanner does not include constructor annotation scanning, use instead Scanners.ConstructorsAnnotated

(3): MethodParameterScanner is obsolete, use instead as required:
Scanners.MethodsParameter, Scanners.MethodsSignature, Scanners.MethodsReturn, Scanners.ConstructorsParameter, Scanners.ConstructorsSignature

</details>

ReflectionUtils

Apart from scanning classpath metadata using Javassist, Java Reflection convenient methods are available using ReflectionsUtils:

import static org.reflections.ReflectionUtils.*;

Set<Class<?>>    superTypes   = get(SuperTypes.of(T));
Set<Field>       fields       = get(Fields.of(T));
Set<Constructor> constructors = get(Constructors.of(T));
Set<Methods>     methods      = get(Methods.of(T));
Set<URL>         resources    = get(Resources.with(T));

Set<Annotation>  annotations  = get(Annotations.of(T));
Set<Class<? extends Annotation>> annotationTypes = get(AnnotationTypes.of(T));

Previous ReflectionUtils 0.9.x API is still supported though marked for removal, more info in the javadocs.

Query API

Each Scanner and ReflectionUtils function implements QueryBuilder, and supports:

For example, Scanners.SubTypes.get(T) return direct subtypes, while Scanners.SubTypes.of(T) return transitive subtypes hierarchy. Same goes for Scanners.TypesAnnotated and ReflectionUtils.SuperTypes etc.

Next, each function implements QueryFunction, and provides fluent functional interface for composing filter(), map(), flatMap(), as() and more, such that:

// filter, as/map
QueryFunction<Store, Method> getters =
  Methods.of(C1.class)
    .filter(withModifier(Modifier.PUBLIC))
    .filter(withPrefix("get").and(withParametersCount(0)))
    .as(Method.class);

// compose Scanners and ReflectionUtils functions 
QueryFunction<Store, Method> methods = 
  SubTypes.of(type).asClass()  // <-- classpath scanned metadata
    .flatMap(Methods::of);     // <-- java reflection api

// function of function
QueryFunction<Store, Class<? extends Annotation>> queryAnnotations = 
  Annotations.of(Methods.of(C4.class))
    .map(Annotation::annotationType);

See more in ReflectionUtilsQueryTest

A more complex example demonstrates getting merged annotations of rest controllers endpoints:

// get all annotations of RequestMapping hierarchy (GetMapping, PostMapping, ...)
Set<Class<?>> metaAnnotations =
  reflections.get(TypesAnnotated.getAllIncluding(RequestMapping.class.getName()).asClass());

QueryFunction<Store, Map<String, Object>> queryAnnotations =
  // get all controller endpoint methods      
  MethodsAnnotated.with(metaAnnotations).as(Method.class)
    .map(method ->
      // get both method's + declaring class's RequestMapping annotations   
      get(Annotations.of(method.getDeclaringClass())
        .add(Annotations.of(method))
        .filter(a -> metaAnnotations.contains(a.annotationType())))
        .stream()
        // merge annotations' member values into a single hash map
        .collect(new AnnotationMergeCollector(method)));

// apply query and map merged hashmap into java annotation proxy
Set<RequestMapping> mergedAnnotations = 
  reflections.get(mergedAnnotation
    .map(map -> ReflectionUtils.toAnnotation(map, metaAnnotation)));

Check the tests folder for more examples and API usage

What else?


Spread the spirit of open-source and collaboration, clean code and simplicity