Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Method Class | getParameterAnnotations() method in Java
Next article icon

Method Class | getAnnotation() method in Java

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The java.lang.reflect.Method.getAnnotation(Class< T > annotationClass) method of Method class returns Method objects’ annotation for the specified type passed as parameter if such an annotation is present, else null. This is important method to get annotation for Method object. Syntax:

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

Parameter: This method takes a mandatory parameter annotationClass which is the Class object of the annotation type. Return Value: This method returns the method’s annotation for the specified annotation type if present on this element, else null. Exception: This method throws NullPointerException if the given annotation class is null Below program illustrates getAnnotation(Class annotationClass) method of Method class: Example 1: This program prints method’s annotation for the specified annotation type given as parameter to getAnnotation() of Method Object representing getCustomAnnotation() method of GFG class. In this example, a single class is used and class contains both methods which are main method and method with annotation. 

Java




// 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

Example 2: This program prints method’s annotation for the specified annotation type given as parameter to getAnnotation() of Method Object representing getCustomAnnotation() method of GFG class. 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. 

Java




// 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

Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getAnnotation-java.lang.Class-



Next Article
Method Class | getParameterAnnotations() method in Java

A

AmanSingh2210
Improve
Article Tags :
  • Java
  • Java-Functions
  • Java-lang package
  • java-lang-reflect-package
  • Java-Method Class
Practice Tags :
  • Java

Similar Reads

  • Method Class | getDeclaredAnnotations() method in Java
    The java.lang.reflect.Method.getDeclaredAnnotations() method of Method class returns annotations declared only on the method and ignores inherited annotations by method. If there are no annotations directly declared on the method, the returned array of annotation is empty. Modification of the return
    3 min read
  • Method Class | getParameterAnnotations() method in Java
    The java.lang.reflect.Method.getParameterAnnotations() method of Method class returns a two-dimensional Annotation array, that represents the annotations on the parameters, of the Method object. If the Method contains no parameters, an empty array will be returned. If the Method contains one or more
    4 min read
  • Method Class | getName() Method in Java
    The getName() method of java.lang.reflect.Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects. Syntax: public String getName() Return Value: It returns the name o
    3 min read
  • Method Class | getAnnotatedReturnType() method in Java
    The java.lang.reflect.Method.getAnnotatedReturnType() method returns an AnnotatedType object which represents AnnotatedType to specify return type of Method Object. If Method object is created for a constructor, then AnnotatedType object specifies the type of the constructed object. If Method object
    3 min read
  • Method Class | getParameterCount() method in Java
    The java.lang.reflect.Method.getParameterCount() method of Method class returns the number of parameters declared on a method Object. Syntax: public int getParameterCount() Return Value: This method returns number of formal parameters defined on this Method Object. Below programs illustrates getPara
    3 min read
  • Class getAnnotation() method in Java with Examples
    The getAnnotation() method of java.lang.Class class is used to get the annotation of the specified annotation type, if such an annotation is present in this class. The method returns that class in the form of an object. Syntax: public T getAnnotation(Class<T> annotationClass) Parameter: This m
    2 min read
  • Class getAnnotations() method in Java with Examples
    The getAnnotations() method of java.lang.Class class is used to get the annotations present in this class. The method returns an array of annotations present. Syntax: public Annotation[] getAnnotations() Parameter: This method does not accepts any parameter. Return Value: This method returns an arra
    2 min read
  • Method Class | getDefaultValue() Method in Java
    The getDefaultValue() method of java.lang.reflect.Method class. It returns the default value for the annotation member represented by the Method object. When annotation member belongs to primitive types, then the method returns the instance of that wrapper type. It returns null if annotation member
    3 min read
  • Method Class | getModifiers() method in Java
    The java.lang.reflect.Method.getModifiers() method of Method class returns the modifiers for the method represented by this Method object. It returns int value. Then with the use Modifier class, the name of modifiers corresponding to that value is fetched. Syntax: public int getModifiers() Return Va
    3 min read
  • Method Class | getReturnType() Method in Java
    Prerequisite : Java.lang.Class class in Java | Set 1, Java.lang.Class class in Java | Set 2The java.lang.reflectMethod Class help in getting information of a single method on a class or interface. This class also provides access to the methods of classes and invoke them at runtime. The getReturnType
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences