Wednesday, 18 September 2013

Java Reflection Notes – getDeclaredAnnotations vs getAnnotations method -vs-getannotations-method

This is just going to be a very short notes about difference between the getDeclaredAnnotations and getAnnotations method of Java java.lang.Class<T> class.
I was googling for the answer but didn’t immediately got any article that explains it, so I thought why I not create it myself.
So what is the difference:
In short:
- getAnnotations basically gets all annotations that are also inherited from the parent class.
- getDeclaredAnnotations gets annotations declared ONLY on the class
If you rather believe what the code says rather than me, here’s the code:

public class CheckTest {

@Retention(RetentionPolicy.RUNTIME)
@Inherited

public @interface CustomAnnotation{
String value();
}
@CustomAnnotation("label")
public static class Parent{
}
public static class Child extends Parent{

}
/**
* @param args
*/
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
System.out.println("Parent class:");
System.out.println("  getDeclaredAnnotations: " +
parent.getClass().getDeclaredAnnotations().length);
System.out.println("  getAnnotations: " +
parent.getClass().getAnnotations().length + "\n");
System.out.println("Child class:");
System.out.println("  getDeclaredAnnotations: " +
child.getClass().getDeclaredAnnotations().length);
System.out.println("  getAnnotations: " +
child.getClass().getAnnotations().length);
 }
}

The output result is:

Parent class:
getDeclaredAnnotations: 1
getAnnotations: 1
Child class:
getDeclaredAnnotations: 0
getAnnotations: 1
Notice that the Child getAnnotations array length is 0, because by itself the Child class doesn't has annotations. :D

Post a Comment