Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java find annotated classes

farenda 2015-08-25 0

Problem:

How to find annotated classes in Java? JDK by itself doesn’t provide such mechanism, but there are libraries that can do that. One of them is Reflections, which is used in the following example.

Solution:

For starter here’s Maven pom.xml with relevant dependencies:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.farenda.java</groupId>
    <artifactId>scanning</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.10</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Now, lets create a custom annotation and attach name as metadata:

package com.farenda.java.lang;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// Make the annotation available at runtime:
@Retention(RetentionPolicy.RUNTIME)
// Allow to use only on types:
@Target(ElementType.TYPE)
public @interface Findable {

    /**
     * User friendly name of annotated class.
     */
    String name();
}

Sample classes annotated with the custom annotation:

package com.farenda.java.lang;

@Findable(name = "Find me")
public class FirstAnnotatedClass {
}
package com.farenda.java.lang;

@Findable(name = "Find me too")
public class SecondAnnotatedClass {
}

In the following Java code we use super simple Reflections library and in one method call find all classes annotated with Findable, our custom annotation:

package com.farenda.java.lang;

import org.reflections.Reflections;

public class ReflectionAnnotatedClasses {

    public static void main(String[] args) {
        System.out.println("Scanning using Reflections:");

        Reflections ref = new Reflections("com.farenda.java.lang");
        for (Class<?> cl : ref.getTypesAnnotatedWith(Findable.class)) {
            Findable findable = cl.getAnnotation(Findable.class);
            System.out.printf("Found class: %s, with meta name: %s%n",
                    cl.getSimpleName(), findable.name());
        }
    }
}

The result goes here:

Scanning using Reflections:
Found class: FirstAnnotatedClass, with meta name: Find me
Found class: SecondAnnotatedClass, with meta name: Find me too

Great and easy to use library! :-)

See Spring classpath scanning for solution that employs mechanism provided by Spring Framework.

Share with the World!
Categories Java Tags java, java-lang
Previous: Spring find annotated classes
Next: Maven package with dependencies

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok