Warning: Use of undefined constant fixed - assumed 'fixed' (this will throw an Error in a future version of PHP) in /home/webtro13/domains/farenda.com/public_html/wp-content/themes/moments/header.php on line 65

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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">





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:
// Allow to use only on types:
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!