AnnotatedElement método getDeclaredAnnotationsByType() en Java con ejemplos

El método getDeclaredAnnotations() de la clase java.lang.AnnotatedElement se utiliza para obtener las anotaciones declaradas del tipo de anotación declarado especificado presente en la clase que implementa esta interfaz. El método devuelve una array de anotaciones declaradas para el tipo de anotación declarado especificado.

Sintaxis:

public A[] getDeclaredAnnotationsByType(Class<T> declared annotationClass)

Parámetro: este método acepta un parámetro declarado annotationClass que es el tipo de anotación declarada que se va a obtener.

Valor devuelto: este método devuelve una array de anotaciones declaradas para el tipo de anotación declarado especificado.

Excepción: este método arroja:

  • NullPointerException: si la clase de anotación declarada dada es nula.

Los siguientes programas muestran el método getDeclaredAnnotationsByType().

Ejemplo 1:

// Java program to demonstrate
// getDeclaredAnnotationsByType() method
  
import java.util.*;
import java.lang.reflect.*;
import java.lang.annotation.*;
  
// create a custom DeclaredAnnotation
@Retention(RetentionPolicy.RUNTIME)
@interface DeclaredAnnotation {
  
    // This declared annotation has two attributes.
    public String key();
  
    public String value();
}
  
// call DeclaredAnnotation for method
// and pass values for declared annotation
@DeclaredAnnotation(key = "GFG", value = "GeeksForGeeks")
public class Test {
  
    public Object obj;
  
    public static void main(String[] args)
        throws ClassNotFoundException
    {
  
        // returns the Class object
        // for this myAnnotatedElement
        AnnotatedElement myAnnotatedElement
            = Test.class;
  
        System.out.println(
            "AnnotatedElement represented"
            + " by myAnnotatedElement: "
            + myAnnotatedElement.toString());
  
        // Get the declared annotation
        // using getDeclaredAnnotationsByType() method
        System.out.println(
            "DeclaredAnnotation of myAnnotatedElement"
            + " of type DeclaredAnnotation: "
            + Arrays.toString(
                  myAnnotatedElement
                      .getDeclaredAnnotationsByType(
                          DeclaredAnnotation.class)));
    }
}
Producción:

AnnotatedElement representado por myAnnotatedElement: clase Test
DeclaredAnnotation de myAnnotatedElement de tipo DeclaredAnnotation: [@DeclaredAnnotation(key=GFG, value=GeeksForGeeks)]

Ejemplo 2:

// Java program to demonstrate
// getDeclaredAnnotationsByType() method
  
import java.util.*;
import java.lang.reflect.*;
import java.lang.annotation.*;
  
@Deprecated
public class Test {
  
    public Object obj;
  
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        try {
  
            // returns the Class object
            // for this myAnnotatedElement
            AnnotatedElement myAnnotatedElement
                = Test.class;
  
            System.out.println(
                "AnnotatedElement represented"
                + " by myAnnotatedElement: "
                + myAnnotatedElement.toString());
  
            // Get the declared annotation
            // using getDeclaredAnnotationsByType() method
            System.out.println(
                "DeclaredAnnotation of myAnnotatedElement"
                + " of type Deprecated: "
                + Arrays.toString(
                      myAnnotatedElement
                          .getDeclaredAnnotationsByType(
                              Deprecated.class)));
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
Producción:

AnnotatedElement representado por myAnnotatedElement: clase Test
DeclaredAnnotation of myAnnotatedElement of type Obsoleto: [@java.lang.Deprecated()]

Referencia: https://docs.oracle.com/javase/9/docs/api/java/lang/reflect/AnnotatedElement.html#getAnnotationsByType-java.lang.Class-

Publicación traducida automáticamente

Artículo escrito por guptayashgupta53 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *