user20110
user20110

Reputation: 151

Reading protected annotation defined in a class using reflection

I have created a class in java as following:

public class TestAnnotations {
    @Retention(value=RetentionPolicy.RUNTIME)
    @Target(value=ElementType.FIELD)
    protected @interface Addition
    {
        String location();
    }
}

How can I get information about the annotation defined in the class using reflection. To be more specific, I am looking for the information like what is the type of Addition, of course name and its fields in it.

Upvotes: 0

Views: 766

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279920

You can use Class#getDeclaredClasses() which

Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object.

You can then iterate over the array, check that that class is an annotation with Class#isAnnotation().

Example

public class Driver {
    public static void main(String[] args) throws Exception {
        Class<?>[] classes = Driver.class.getDeclaredClasses();
        System.out.println(Arrays.toString(classes));
        for (Class<?> clazz : classes) {
            if (clazz.isAnnotation()) {
                Method[] methods = clazz.getDeclaredMethods();
                for (Method method : methods) {
                    System.out.println(method);
                }
            }
        }
    }

    @Retention(value=RetentionPolicy.RUNTIME)
    @Target(value=ElementType.FIELD)
    protected @interface Addition
    {
        String location();
    }
}

prints

[interface com.spring.Driver$Addition]
public abstract java.lang.String com.spring.Driver$Addition.location()

Upvotes: 2

Related Questions