Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Introduction

The Reflections library works as a classpath scanner. It indexes the scanned metadata and allows us to query it at runtime. It can also save this information, so we can collect and use it at any point during our project, without having to re-scan the classpath again.

In this tutorial, we'll show how to configure the Reflections library and use it in our Java projects.

2. Maven Dependency

To use Reflections, we need to include its dependency in our project:

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.11</version>
</dependency>

We can find the latest version of the library on Maven Central.

3. Configuring Reflections

Next, we need to configure the library. The main elements of the configuration are the URLs and scanners.

The URLs tell the library which parts of the classpath to scan, whereas the scanners are the objects that scan the given URLs.

In the event that no scanner is configured, the library uses TypeAnnotationsScanner and SubTypesScanner as the default ones.

3.1. Adding URLs

We can configure Reflections either by providing the configuration's elements as the varargs constructor's parameters, or by using the ConfigurationBuilder object.

For instance, we can add URLs by instantiating Reflections using a String representing the package name, the class, or the class loader:

Reflections reflections = new Reflections("com.baeldung.reflections");
Reflections reflections = new Reflections(MyClass.class);
Reflections reflections = new Reflections(MyClass.class.getClassLoader());

Moreover, because Reflections has a varargs constructor, we can combine all the above configurations' types to instantiate it:

Reflections reflections = new Reflections("com.baeldung.reflections", MyClass.class);

Here, we are adding URLs by specifying the package and the class to scan.

We can achieve the same results by using the ConfigurationBuilder:

Reflections reflections = new Reflections(new ConfigurationBuilder()
  .setUrls(ClasspathHelper.forPackage("com.baeldung.reflections"))));

Together with the forPackage() method, ClasspathHelper provides other methods, such as forClass() and forClassLoader(), to add URLs to the configuration.

3.2. Adding Scanners

The Reflections library comes with many built-in scanners:

  • FieldAnnotationsScanner – looks for field's annotations
  • MethodParameterScanner – scans methods/constructors, then indexes parameters, and returns type and parameter annotations
  • MethodParameterNamesScanner – inspects methods/constructors, then indexes parameter names
  • TypeElementsScanner – examines fields and methods, then stores the fully qualified name as a key, and elements as values
  • MemberUsageScanner – scans methods/constructors/fields usages
  • TypeAnnotationsScanner – looks for class's runtime annotations
  • SubTypesScanner – searches for super classes and interfaces of a class, allowing a reverse lookup for subtypes
  • MethodAnnotationsScanner – scans for method's annotations
  • ResourcesScanner – collects all non-class resources in a collection

We can add scanners to the configuration as parameters of Reflections‘ constructor.

For instance, let's add the first two scanners from the above list:

Reflections reflections = new Reflections("com.baeldung.reflections"), 
  new FieldAnnotationsScanner(), 
  new MethodParameterScanner());

Again, the two scanners can be configured by using the ConfigurationBuilder helper class:

Reflections reflections = new Reflections(new ConfigurationBuilder()
  .setUrls(ClasspathHelper.forPackage("com.baeldung.reflections"))
  .setScanners(new FieldAnnotationsScanner(), new MethodParameterScanner()));

3.3. Adding the ExecutorService

In addition to URLs and scanners, Reflections gives us the possibility to asynchronously scan the classpath by using the ExecutorService.

We can add it as a parameter of Reflections‘ constructor, or through the ConfigurationBuilder:

Reflections reflections = new Reflections(new ConfigurationBuilder()
  .setUrls(ClasspathHelper.forPackage("com.baeldung.reflections"))
  .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner())
  .setExecutorService(Executors.newFixedThreadPool(4)));

Another option is to simply call the useParallelExecutor() method. This method configures a default FixedThreadPool ExecutorService with a size equal to the number of the available core processors.

3.4. Adding Filters

Another important configurations element is a filter. A filter tells the scanners what to include, and what to exclude, when scanning the classpath.

As an illustration, we can configure the filter to exclude scanning of the test package:

Reflections reflections = new Reflections(new ConfigurationBuilder()
  .setUrls(ClasspathHelper.forPackage("com.baeldung.reflections"))
  .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner())
  .filterInputsBy(new FilterBuilder().excludePackage("com.baeldung.reflections.test")));

Now, up to this point, we've made a quick overview of the different elements of Reflections‘ configuration. Next, we'll see how to use the library.

4. Querying Using Reflections

After calling one of the Reflections constructors, the configured scanners scan all the provided URLs. Then, for each scanner, the library puts the results in Multimap stores. As a result, in order to use Reflections, we need to query these stores by calling the provided query methods.

Let's see some examples of these query methods.

4.1. Subtypes

Let's start by retrieving all the scanners provided by Reflections:

public Set<Class<? extends Scanner>> getReflectionsSubTypes() {
    Reflections reflections = new Reflections(
      "org.reflections", new SubTypesScanner());
    return reflections.getSubTypesOf(Scanner.class);
}

4.2. Annotated Types

Next, we can get all the classes and interfaces that implement a given annotation.

So, let's retrieve all the functional interfaces of the java.util.function package:

public Set<Class<?>> getJDKFunctinalInterfaces() {
    Reflections reflections = new Reflections("java.util.function", 
      new TypeAnnotationsScanner());
    return reflections.getTypesAnnotatedWith(FunctionalInterface.class);
}

4.3. Annotated Methods

Now, let's use the MethodAnnotationsScanner to get all the methods annotated with a given annotation:

public Set<Method> getDateDeprecatedMethods() {
    Reflections reflections = new Reflections(
      "java.util.Date", 
      new MethodAnnotationsScanner());
    return reflections.getMethodsAnnotatedWith(Deprecated.class);
}

4.4. Annotated Constructors

Also, we can get all the deprecated constructors:

public Set<Constructor> getDateDeprecatedConstructors() {
    Reflections reflections = new Reflections(
      "java.util.Date", 
      new MethodAnnotationsScanner());
    return reflections.getConstructorsAnnotatedWith(Deprecated.class);
}

4.5. Methods' Parameters

Additionally, we can use MethodParameterScanner to find all the methods with a given parameter type:

public Set<Method> getMethodsWithDateParam() {
    Reflections reflections = new Reflections(
      java.text.SimpleDateFormat.class, 
      new MethodParameterScanner());
    return reflections.getMethodsMatchParams(Date.class);
}

4.6. Methods' Return Type

Furthermore, we can also use the same scanner to get all the methods with a given return type.

Let's imagine that we want to find all the methods of the SimpleDateFormat that return void:

public Set<Method> getMethodsWithVoidReturn() {
    Reflections reflections = new Reflections(
      "java.text.SimpleDateFormat", 
      new MethodParameterScanner());
    return reflections.getMethodsReturn(void.class);
}

4.7. Resources

Finally, let's use the ResourcesScanner to look for a given filename in our classpath:

public Set<String> getPomXmlPaths() {
    Reflections reflections = new Reflections(new ResourcesScanner());
    return reflections.getResources(Pattern.compile(".*pom\\.xml"));
}

4.8. Additional Query Methods

The above were but a handful of examples showing how to use Reflections' query methods. Yet, there are other query methods that we haven't covered here:

  • getMethodsWithAnyParamAnnotated
  • getConstructorsMatchParams
  • getConstructorsWithAnyParamAnnotated
  • getFieldsAnnotatedWith
  • getMethodParamNames
  • getConstructorParamNames
  • getFieldUsage
  • getMethodUsage
  • getConstructorUsage

5. Integrating Reflections into a Build Lifecycle

We can easily integrate Reflections into our Maven build using the gmavenplus-plugin.

Let's configure it to save the result of scans to a file:

<plugin>
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.5</version>
    <executions>
        <execution>
            <phase>generate-resources</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <scripts>
                    <script><![CDATA[
                        new org.reflections.Reflections(
                          "com.baeldung.refelections")
                            .save("${outputDirectory}/META-INF/reflections/reflections.xml")]]>
                    </script>
                </scripts>
            </configuration>
        </execution>
    </executions>
</plugin>

Later on, by calling the collect() method, we can retrieve the saved results and make them available for further use, without having to perform a new scan:

Reflections reflections
  = isProduction() ? Reflections.collect() : new Reflections("com.baeldung.reflections");

6. Conclusion

In this article, we explored the Reflections library. We covered different configuration elements and their usages. And, finally, we saw how to integrate Reflections into a Maven project's build lifecycle.

As always, the complete code is available over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!