This method returns
this class annotation for the specified type if such an annotation is directly present, else null. This
method ignores inherited annotations.
package com.logicbig.example.clazz;
import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class GetDeclaredAnnotationExample {
public static void main(String... args) {
System.out.println("-- declared annotations --");
Annotation a = MyClass.class.getDeclaredAnnotation(Deprecated.class);
System.out.println(a);
a = MyClass.class.getDeclaredAnnotation(MyAnnotation.class);
System.out.println(a);
System.out.println("-- annotations --");
a = MyClass.class.getAnnotation(Deprecated.class);
System.out.println(a);
a = MyClass.class.getAnnotation(MyAnnotation.class);
System.out.println(a);
}
@Deprecated
public static class MyClass extends MySuperClass {
}
@MyAnnotation
public static class MySuperClass {
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
private static @interface MyAnnotation {
}
}
Output
-- declared annotations --
@java.lang.Deprecated(forRemoval=false, since="")
null
-- annotations --
@java.lang.Deprecated(forRemoval=false, since="")
@com.logicbig.example.clazz.GetDeclaredAnnotationExample$MyAnnotation()
package com.logicbig.example.clazz;
import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class GetDeclaredAnnotationExample2 {
public static void main(String... args) {
System.out.println("-- declared annotations --");
Annotation a = MyClass.class.getDeclaredAnnotation(Deprecated.class);
System.out.println(a);
a = MyClass.class
.getDeclaredAnnotation(MyAnnotation.class);
System.out.println(a);
System.out.println("-- annotations --");
a = MyClass.class.getAnnotation(Deprecated.class);
System.out.println(a);
a = MyClass.class.getAnnotation(MyAnnotation.class);
System.out.println(a);
}
@Deprecated
public static class MyClass implements MyInterface {
}
@MyAnnotation
public static interface MyInterface {
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
private static @interface MyAnnotation {
}
}
Output
-- declared annotations --
@java.lang.Deprecated(forRemoval=false, since="")
null
-- annotations --
@java.lang.Deprecated(forRemoval=false, since="")
null