Класс метода | getAnnotation () в Java

Опубликовано: 12 Февраля, 2022

Метод java.lang.reflect.Method.getAnnotation (Class <T> annotationClass) класса Method возвращает аннотацию объектов метода для указанного типа, переданного в качестве параметра, если такая аннотация присутствует, иначе null. Это важный метод получения аннотации для объекта Method.

Синтаксис:

 public <T extends Annotation> T getAnnotation (Class <T> annotationClass)

Параметр: этот метод принимает обязательный параметр annotationClass, который является объектом Class типа аннотации.

Возвращаемое значение: этот метод возвращает аннотацию метода для указанного типа аннотации, если она присутствует в этом элементе, иначе null.

Исключение: этот метод выдает исключение NullPointerException, если данный класс аннотации имеет значение NULL.

Программа ниже иллюстрирует метод getAnnotation (Class annotationClass) класса Method:

Пример 1. Эта программа печатает аннотацию метода для указанного типа аннотации, заданного в качестве параметра для getAnnotation () объекта Method, представляющего метод getCustomAnnotation () класса GFG.

In thi,s example a single class is used and class contains both methods which are main method and method with annotation.

// Program Demonstrate getAnnotation(Class<T> annotationClass) method
// of Method Class.
  
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
  
// create a custom Annotation
@Retention(RetentionPolicy.RUNTIME)
@interface Annotation {
  
    // This annotation has two attributes.
    public String key();
  
    public String value();
}
  
// create the Main Class
public class GFG {
  
    // call Annotation for method and pass values for annotation
    @Annotation(key = "AvengersLeader", value = "CaptainAmerica")
    public static void getCustomAnnotation()
    {
  
        try {
  
            // create class object for class name GFG
            Class c = GFG.class;
  
            // get method name getCustomAnnotation as Method object
            Method[] methods = c.getMethods();
            Method method = null;
            for (Method m : methods) {
                if (m.getName().equals("getCustomAnnotation"))
                    method = m;
            }
  
            // get Annotation of Method object m by passing
            // Annotation class object as parameter
            Annotation anno = method.getAnnotation(Annotation.class);
  
            // print Annotation Details
            System.out.println("Annotation for Method Object"
                               + " having name: " + method.getName());
            System.out.println("Key Attribute of Annotation: "
                               + anno.key());
            System.out.println("Value Attribute of Annotation: "
                               + anno.value());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
  
    // create main method
    public static void main(String args[])
    {
        getCustomAnnotation();
    }
}
Output:
Annotation for Method Object having name: getCustomAnnotation
Key Attribute of Annotation: AvengersLeader
Value Attribute of Annotation: CaptainAmerica

Пример 2: Эта программа печатает аннотацию метода для указанного типа аннотации, заданного в качестве параметра для getAnnotation () объекта Method, представляющего метод getCustomAnnotation () класса GFG.

In this example a two classes is used.One class contains main method which creates the method object and applying getAnnotation() method and other class contains method with some annotation.

// Program Demonstrate getAnnotation(Class<T> annotationClass) method
// of Method Class.
  
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // get array Method objects
        Method[] methods = GFGDemoClass.class.getMethods();
  
        // get Annotation
        SelfCreatedAnnotation annotation = methods[0]
                                               .getAnnotation(
                                                   SelfCreatedAnnotation
                                                       .class);
  
        // Print annotation attribute
        System.out.println("key: " + annotation.key());
        System.out.println("value: " + annotation.value());
    }
}
  
// Another class on which we want to apply the annotation
class GFGDemoClass {
    private String field;
  
    // create annotation
    @SelfCreatedAnnotation(key = "getField",
                           value = "getting field attribute")
    public String
    getField()
    {
        return field;
    }
}
  
// create custom annotation having two values
@Retention(RetentionPolicy.RUNTIME)
@interface SelfCreatedAnnotation {
    public String key();
    public String value();
}
Output:
key: getField
value: getting field attribute

Ссылка: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getAnnotation-java.lang.Class-

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .