Java Programming Tutorials

Java programming tutorials with many code examples!

Java find annotated classes


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.


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

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""





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


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:
// Allow to use only on types:
public @interface Findable {

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

Sample classes annotated with the custom annotation:


@Findable(name = "Find me")
public class FirstAnnotatedClass {

@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:


import org.reflections.Reflections;

public class ReflectionAnnotatedClasses {

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

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

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.

Was it helpful? Share!