Close

Java Reflection - Class.getDeclaredAnnotations() Examples

Java Reflection Java Java API 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Method:

public Annotation[] getDeclaredAnnotations()

This method returns annotations that are directly present on this class. This method ignores inherited annotations.

Returns:
annotations directly present on this element


Examples


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;
import java.util.Arrays;

public class GetDeclaredAnnotationsExample {

public static void main(String... args) {
System.out.println("-- declared annotations --");
Annotation[] a = MyClass.class.getDeclaredAnnotations();
System.out.println(Arrays.toString(a));

System.out.println("-- annotations --");
a = MyClass.class.getAnnotations();
System.out.println(Arrays.toString(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="")]
-- annotations --
[@com.logicbig.example.clazz.GetDeclaredAnnotationsExample$MyAnnotation(), @java.lang.Deprecated(forRemoval=false, since="")]




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;
import java.util.Arrays;

public class GetDeclaredAnnotationsExample2 {

public static void main(String... args) {
System.out.println("-- declared annotations --");
Annotation[] a = MyClass.class.getDeclaredAnnotations();
System.out.println(Arrays.toString(a));

System.out.println("-- annotations --");
a = MyClass.class.getAnnotations();
System.out.println(Arrays.toString(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="")]
-- annotations --
[@java.lang.Deprecated(forRemoval=false, since="")]




See Also