- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Lists with Java Annotations
I want to validate my arguments with Java Annotation. I don't know how to use write a own Annotation for Lists.
Here an simple example:
my Annotation Interface:
In this Example my List is valid, if each element from my List has another name. I don't know how I get the listobject in my Validator class and the names of myObject-elements.
I try to describe my question in another way:
my list is not valid if two elements from type "myObject" in my list ("myElements") have the same name!
How could I realize this with Annotations?
- annotations
- bean-validation

- Is there any specific reason to choose annotations over some decorated list? – Dilum Ranatunga Oct 31, 2012 at 17:40
- have you looked at stackoverflow.com/questions/7865209/… – Martin Serrano Oct 31, 2012 at 18:05
2 Answers 2
In the initialize method you can get the values, which are defined in the annotation. The isValid method is used to validate the object (objectToValidate -> your list object).
For more information on how to write a custom validator see http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-customconstraints.html#validator-customconstraints-validator
Also the Hibernate-Validator implementation is a good reference. https://github.com/hibernate/hibernate-validator/tree/master/engine/src/main/java/org/hibernate/validator/internal/constraintvalidators
I hope this answer helps you.

I can answer your question partly, you can get names out from the collection which is sent as parameter in your isValid method. Iterate your collection (which in your case a list).

- what do you mean with "my test-object is not available". The way to go is to iterate the collection passed to you. This is the collection you placed the custom constraint annotation on, aka myElements . – Hardy Nov 1, 2012 at 11:25
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged java annotations bean-validation or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- What is the name of the color used by the SBB (Swiss Federal Railway) in the 1920s to paint their locomotive?
- Will DL360 Gen 8 servers fit in rails designed for DL360 Gen 7 servers?
- Do new devs get fired if they can't solve a certain bug?
- Is there a non-constant function on the sphere that diagonalizes all rotations simultaneously?
- Minimising the environmental effects of my dyson brain
- Is it ok to run post hoc comparisons if ANOVA is nearly significant?
- "Is" or "are" for two uncountable words?
- Euler: “A baby on his lap, a cat on his back — that’s how he wrote his immortal works” (origin?)
- Should sticker on top of HDD be peeled?
- Is this summary of MCMC correct?
- Covering of a knot complement
- What did Ctrl+NumLock do?
- Google maps for Space exploration
- Align vertically 2 circuits
- How do/should administrators estimate the cost of producing an online introductory mathematics class?
- Choice of Basis for solution space of a Hamiltonian
- Does melting sea ices rises global sea level?
- Quotients of number fields by certain prime powers
- What video game is Charlie playing in Poker Face S01E07?
- Lagrange Points in General Relativity
- Active thermistor giving skewed readings immediately when heating element turned on
- How can I measure the power in mW of a radio signal?
- Linear Algebra - Linear transformation question
- For the Nozomi from Shinagawa to Osaka, say on a Saturday afternoon, would tickets/seats typically be available - or would you need to book?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
Learn Java interactively.
Learn Java practically and Get Certified .
Popular Tutorials
Popular examples, reference materials.
Learn Java Interactively
Java Introduction
- Java Hello World
- Java JVM, JRE and JDK
- Java Variables and Literals
- Java Data Types
- Java Operators
- Java Input and Output
- Java Expressions & Blocks
- Java Comment
Java Flow Control
- Java if...else
- Java switch Statement
- Java for Loop
- Java for-each Loop
- Java while Loop
- Java break Statement
- Java continue Statement
- Java Arrays
- Multidimensional Array
- Java Copy Array
Java OOP (I)
- Java Class and Objects
- Java Methods
- Java Method Overloading
- Java Constructor
- Java Strings
- Java Access Modifiers
- Java this keyword
- Java final keyword
- Java Recursion
- Java instanceof Operator
Java OOP (II)
Java Inheritance
Java Method Overriding
- Java super Keyword
- Abstract Class & Method
- Java Interfaces
- Java Polymorphism
- Java Encapsulation
Java OOP (III)
- Nested & Inner Class
- Java Static Class
- Java Anonymous Class
- Java Singleton
- Java enum Class
- Java enum Constructor
- Java enum String
- Java Reflection
- Java Exception Handling
- Java Exceptions
- Java try...catch
- Java throw and throws
- Java catch Multiple Exceptions
- Java try-with-resources
Java Annotations
Java Annotation Types
- Java Logging
- Java Assertions
- Java Collections Framework
- Java Collection Interface
- Java List Interface
- Java ArrayList
- Java Vector
- Java Queue Interface
- Java PriorityQueue
- Java Deque Interface
- Java LinkedList
- Java ArrayDeque
- Java BlockingQueue Interface
- Java ArrayBlockingQueue
- Java LinkedBlockingQueue
- Java Map Interface
- Java HashMap
- Java LinkedHashMap
- Java WeakHashMap
- Java EnumMap
- Java SortedMap Interface
- Java NavigableMap Interface
- Java TreeMap
- Java ConcurrentMap Interface
- Java ConcurrentHashMap
- Java Set Interface
- Java HashSet
- Java EnumSet
- Java LinkedhashSet
- Java SortedSet Interface
- Java NavigableSet Interface
- Java TreeSet
- Java Algorithms
- Java Iterator
- Java ListIterator
- Java I/O Streams
- Java InputStream
- Java OutputStream
- Java FileInputStream
- Java FileOutputStream
- Java ByteArrayInputStream
- Java ByteArrayOutputStream
- Java ObjectInputStream
- Java ObjectOutputStream
- Java BufferedInputStream
- Java BufferedOutputStream
- Java PrintStream
Java Reader/Writer
- Java Reader
- Java Writer
- Java InputStreamReader
- Java OutputStreamWriter
- Java FileReader
- Java FileWriter
- Java BufferedReader
- Java BufferedWriter
- Java StringReader
- Java StringWriter
- Java PrintWriter
Additional Topics
- Java Scanner Class
- Java Type Casting
- Java autoboxing and unboxing
- Java Lambda Expression
- Java Generics
- Java File Class
- Java Wrapper Class
- Java Command Line Arguments
Related Topics
Java Lambda Expressions
- Java Abstract Class and Abstract Methods
In this tutorial, we will learn about different types of Java annotation with the help of examples.
Java annotations are metadata (data about data) for our program source code. There are several predefined annotations provided by the Java SE. Moreover, we can also create custom annotations as per our needs.
If you do not know what annotations are, visit the Java annotations tutorial.
These annotations can be categorized as:
1. Predefined annotations
- @Deprecated
- @SuppressWarnings
- @SafeVarargs
- @FunctionalInterface
2. Custom annotations
3. Meta-annotations
- @Documented
- @Repeatable
- Predefined Annotation Types
1. @Deprecated
The @Deprecated annotation is a marker annotation that indicates the element (class, method, field, etc) is deprecated and has been replaced by a newer element.
Its syntax is:
When a program uses the element that has been declared deprecated, the compiler generates a warning.
We use Javadoc @deprecated tag for documenting the deprecated element.
Example 1: @Deprecated annotation example
2. @override.
The @Override annotation specifies that a method of a subclass overrides the method of the superclass with the same method name, return type, and parameter list.
It is not mandatory to use @Override when overriding a method. However, if we use it, the compiler gives an error if something is wrong (such as wrong parameter type) while overriding the method.
Example 2: @Override annotation example
In this example, by making an object dog1 of Dog class, we can call its method printMessage() which then executes the display() statement.
Since display() is defined in both the classes, the method of subclass Dog overrides the method of superclass Animal . Hence, the display() of the subclass is called.
3. @SuppressWarnings
As the name suggests, the @SuppressWarnings annotation instructs the compiler to suppress warnings that are generated while the program executes.
We can specify the type of warnings to be suppressed. The warnings that can be suppressed are compiler-specific but there are two categories of warnings: deprecation and unchecked .
To suppress a particular category of warning, we use:
For example,
To suppress multiple categories of warnings, we use:
Category deprecated instructs the compiler to suppress warnings when we use a deprecated element.
Category unchecked instructs the compiler to suppress warnings when we use raw types.
And, undefined warnings are ignored. For example,
Example 3: @SuppressWarnings annotation example
Here, deprecatedMethod() has been marked as deprecated and will give compiler warnings when used. By using the @SuppressWarnings("deprecated") annotation, we can avoid compiler warnings.
4. @SafeVarargs
The @SafeVarargs annotation asserts that the annotated method or constructor does not perform unsafe operations on its varargs (variable number of arguments).
We can only use this annotation on methods or constructors that cannot be overridden. This is because the methods that override them might perform unsafe operations.
Before Java 9, we could use this annotation only on final or static methods because they cannot be overridden. We can now use this annotation for private methods as well.
Example 4: @SafeVarargs annotation example
Here, List ... lists specifies a variable-length argument of type List . This means that the method displayList() can have zero or more arguments.
The above program compiles without errors but gives warnings when @SafeVarargs annotation isn't used.
When we use @SafeVarargs annotation in the above example,
We get the same output but without any warnings. Unchecked warnings are also suppressed when we use this annotation.
5. @FunctionalInterface
Java 8 first introduced this @FunctionalInterface annotation. This annotation indicates that the type declaration on which it is used is a functional interface. A functional interface can have only one abstract method.
Example 5: @FunctionalInterface annotation example
If we add another abstract method, let's say
Now, when we run the program, we will get the following warning:
It is not mandatory to use @FunctionalInterface annotation. The compiler will consider any interface that meets the functional interface definition as a functional interface.
We use this annotation to make sure that the functional interface has only one abstract method.
However, it can have any number of default and static methods because they have an implementation.
- Custom Annotations
It is also possible to create our own custom annotations.
Here is what you need to know about custom annotation:
- Annotations can be created by using @interface followed by the annotation name.
- The annotation can have elements that look like methods but they do not have an implementation.
- The default value is optional. The parameters cannot have a null value.
- The return type of the method can be primitive, enum, string, class name or array of these types.
Example 6: Custom annotation example
- Meta Annotations
Meta-annotations are annotations that are applied to other annotations.
1. @Retention
The @Retention annotation specifies the level up to which the annotation will be available.
There are 3 types of retention policies:
- RetentionPolicy.SOURCE - The annotation is available only at the source level and is ignored by the compiler.
- RetentionPolicy.CLASS - The annotation is available to the compiler at compile-time, but is ignored by the Java Virtual Machine (JVM).
- RetentionPolicy.RUNTIME - The annotation is available to the JVM.
2. @Documented
By default, custom annotations are not included in the official Java documentation . To include our annotation in the Javadoc documentation, we use the @Documented annotation.
We can restrict an annotation to be applied to specific targets using the @Target annotation.
The ElementType can have one of the following types:
In this example, we have restricted the use of this annotation to methods only.
Note: If the target type is not defined, the annotation can be used for any element.
4. @Inherited
By default, an annotation type cannot be inherited from a superclass. However, if we need to inherit an annotation from a superclass to a subclass, we use the @Inherited annotation.
5. @Repeatable
An annotation that has been marked by @Repeatable can be applied multiple times to the same declaration.
The value defined in the @Repeatable annotation is the container annotation. The container annotation has a variable value of array type of the above repeatable annotation. Here, Universities are the containing annotation type.
Now, the @University annotation can be used multiple times on the same declaration.
If we need to retrieve the annotation data, we can use the Reflection API .
To retrieve annotation values, we use getAnnotationsByType() or getAnnotations() method defined in the Reflection API.
Table of Contents
Sorry about that.
Related Tutorials
Java Tutorial
Try PRO for FREE
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Android App Development with Kotlin(Live)
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- React JS (Basic to Advanced)
- JavaScript Foundation
- Complete Data Science Program(Live)
- Mastering Data Analytics
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
Annotations in Java
- Serialization and Deserialization in Java with Example
- transient keyword in Java
- volatile Keyword in Java
- strictfp keyword in java
- Native Keyword in Java
- Marker interface in Java
- Functional Interfaces in Java
- Lambda Expressions in Java 8
- Stream In Java
- throw and throws in Java
- User-defined Custom Exception in Java
- Infinity or Exception in Java when divide by 0?
- Java Multiple Catch Block
- Chained Exceptions in Java
- Null Pointer Exception In Java
- Output of Java program | Set 12(Exception Handling)
- Java | Exception Handling | Question 1
- Java | Exception Handling | Question 2
- Java | Exception Handling | Question 3
- Java | Exception Handling | Question 4
- Java | Exception Handling | Question 8
- Java | Exception Handling | Question 6
- Java | Exception Handling | Question 7
- Arrays in Java
- Spring Boot - Start/Stop a Kafka Listener Dynamically
- Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
- Split() String method in Java with examples
- Arrays.sort() in Java with examples
- Difficulty Level : Hard
- Last Updated : 25 Oct, 2022
Annotations are used to provide supplemental information about a program.
- Annotations start with ‘ @ ’.
- Annotations do not change the action of a compiled program.
- Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc.
- Annotations are not pure comments as they can change the way a program is treated by the compiler. See below code for example.
- Annotations basically are used to provide additional information, so could be an alternative to XML and Java marker interfaces.
Hierarchy of Annotations in Java
Implementation:
Note: This program throws compiler error because we have mentioned override, but not overridden, we have overloaded display.
Output:
If we remove parameter (int x) or we remove @override, the program compiles fine.
Categories of Annotations
There are broadly 5 categories of annotations as listed:
- Marker Annotations
- Single value Annotations
- Full Annotations
- Type Annotations
- Repeating Annotations
Let us discuss and we will be appending code wherever required if so.
Category 1: Marker Annotations
The only purpose is to mark a declaration. These annotations contain no members and do not consist of any data. Thus, its presence as an annotation is sufficient. Since the marker interface contains no members, simply determining whether it is present or absent is sufficient. @Override is an example of Marker Annotation.
Category 2: Single value Annotations
These annotations contain only one member and allow a shorthand form of specifying the value of the member. We only need to specify the value for that member when the annotation is applied and don’t need to specify the name of the member. However, in order to use this shorthand, the name of the member must be a value.

Category 3: Full Annotations
These annotations consist of multiple data members, names, values, pairs.
Category 4: Type Annotations
These annotations can be applied to any place where a type is being used. For example, we can annotate the return type of a method. These are declared annotated with @Target annotation .
Category 5: Repeating Annotations
These are the annotations that can be applied to a single item more than once. For an annotation to be repeatable it must be annotated with the @Repeatable annotation, which is defined in the java.lang.annotation package. Its value field specifies the container type for the repeatable annotation. The container is specified as an annotation whose value field is an array of the repeatable annotation type. Hence, to create a repeatable annotation, firstly the container annotation is created, and then the annotation type is specified as an argument to the @Repeatable annotation.
Predefined/ Standard Annotations
Java popularly defines seven built-in annotations as we have seen up in the hierarchy diagram.
- Four are imported from java.lang.annotation: @Retention , @Documented , @Target , and @Inherited .
- Three are included in java.lang: @Deprecated, @Override and @SuppressWarnings
Annotation 1: @Deprecated
- It is a marker annotation. It indicates that a declaration is obsolete and has been replaced by a newer form.
- The Javadoc @deprecated tag should be used when an element has been deprecated.
- @deprecated tag is for documentation and @Deprecated annotation is for runtime reflection.
- @deprecated tag has higher priority than @Deprecated annotation when both are together used.
Annotation 2: @Override
It is a marker annotation that can be used only on methods. A method annotated with @Override must override a method from a superclass. If it doesn’t, a compile-time error will result (see this for example). It is used to ensure that a superclass method is actually overridden, and not simply overloaded.
Annotation 3: @SuppressWarnings
It is used to inform the compiler to suppress specified compiler warnings. The warnings to suppress are specified by name, in string form. This type of annotation can be applied to any type of declaration.
Java groups warnings under two categories. They are deprecated and unchecked . Any unchecked warning is generated when a legacy code interfaces with a code that uses generics.
Annotation 4: @Documented
It is a marker interface that tells a tool that an annotation is to be documented. Annotations are not included in ‘Javadoc’ comments. The use of @Documented annotation in the code enables tools like Javadoc to process it and include the annotation type information in the generated document.
Annotation 5: @Target
It is designed to be used only as an annotation to another annotation. @Target takes one argument, which must be constant from the ElementType enumeration. This argument specifies the type of declarations to which the annotation can be applied. The constants are shown below along with the type of the declaration to which they correspond.
We can specify one or more of these values in a @Target annotation. To specify multiple values, we must specify them within a braces-delimited list. For example, to specify that an annotation applies only to fields and local variables, you can use this @Target annotation: @Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE}) @Retention Annotation It determines where and how long the annotation is retent. The 3 values that the @Retention annotation can have:
- SOURCE: Annotations will be retained at the source level and ignored by the compiler.
- CLASS: Annotations will be retained at compile-time and ignored by the JVM.
- RUNTIME: These will be retained at runtime.
Annotation 6: @Inherited
@Inherited is a marker annotation that can be used only on annotation declaration. It affects only annotations that will be used on class declarations. @Inherited causes the annotation for a superclass to be inherited by a subclass. Therefore, when a request for a specific annotation is made to the subclass, if that annotation is not present in the subclass, then its superclass is checked. If that annotation is present in the superclass, and if it is annotated with @Inherited, then that annotation will be returned.
Annotation 7: User-defined (Custom)
User-defined annotations can be used to annotate program elements, i.e. variables, constructors, methods, etc. These annotations can be applied just before the declaration of an element (constructor, method, classes, etc).
Syntax: Declaration
Do keep these certain points as rules for custom annotations before implementing user-defined annotations.
- AnnotationName is an interface.
- The parameter should not be associated with method declarations and throws clause should not be used with method declaration.
- Parameters will not have a null value but can have a default value.
- default value is optional.
- The return type of method should be either primitive, enum, string, class name, or array of primitive, enum, string, or class name type.
This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...
- CharchitKapoor
- solankimayank
- prakharsinha2k2
- java-basics
Improve your Coding Skills with Practice
Start your coding journey now.
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
Annotations Basics
The format of an annotation.
In its simplest form, an annotation looks like the following:
The at sign character ( @ ) indicates to the compiler that what follows is an annotation. In the following example, the annotation's name is Override :
The annotation can include elements , which can be named or unnamed, and there are values for those elements:
If there is just one element named value , then the name can be omitted, as in:
If the annotation has no elements, then the parentheses can be omitted, as shown in the previous @Override example.
It is also possible to use multiple annotations on the same declaration:
If the annotations have the same type, then this is called a repeating annotation:
Repeating annotations are supported as of the Java SE 8 release. For more information, see Repeating Annotations .
The annotation type can be one of the types that are defined in the java.lang or java.lang.annotation packages of the Java SE API. In the previous examples, Override and SuppressWarnings are predefined Java annotations . It is also possible to define your own annotation type. The Author and Ebook annotations in the previous example are custom annotation types.
Where Annotations Can Be Used
Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line.
As of the Java SE 8 release, annotations can also be applied to the use of types. Here are some examples:
- Class instance creation expression: new @Interned MyObject();
- Type cast: myString = (@NonNull String) str;
- implements clause: class UnmodifiableList<T> implements @Readonly List<@Readonly T> { ... }
- Thrown exception declaration: void monitorTemperature() throws @Critical TemperatureException { ... }
This form of annotation is called a type annotation . For more information, see Type Annotations and Pluggable Type Systems .
About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights
Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.
Kotlin Help
Annotations.
Annotations are means of attaching metadata to code. To declare an annotation, put the annotation modifier in front of a class:
Additional attributes of the annotation can be specified by annotating the annotation class with meta-annotations:
@Target specifies the possible kinds of elements which can be annotated with the annotation (such as classes, functions, properties, and expressions);
@Retention specifies whether the annotation is stored in the compiled class files and whether it's visible through reflection at runtime (by default, both are true);
@Repeatable allows using the same annotation on a single element multiple times;
@MustBeDocumented specifies that the annotation is part of the public API and should be included in the class or method signature shown in the generated API documentation.
If you need to annotate the primary constructor of a class, you need to add the constructor keyword to the constructor declaration, and add the annotations before it:
You can also annotate property accessors:
Constructors
Annotations can have constructors that take parameters.
Allowed parameter types are:
Types that correspond to Java primitive types (Int, Long etc.)
Classes ( Foo::class )
Other annotations
Arrays of the types listed above
Annotation parameters cannot have nullable types, because the JVM does not support storing null as a value of an annotation attribute.
If an annotation is used as a parameter of another annotation, its name is not prefixed with the @ character:
If you need to specify a class as an argument of an annotation, use a Kotlin class ( KClass ). The Kotlin compiler will automatically convert it to a Java class, so that the Java code can access the annotations and arguments normally.
Instantiation
In Java, an annotation type is a form of an interface, so you can implement it and use an instance. As an alternative to this mechanism, Kotlin lets you call a constructor of an annotation class in arbitrary code and similarly use the resulting instance.
Learn more about instantiation of annotation classes in this KEEP .
Annotations can also be used on lambdas. They will be applied to the invoke() method into which the body of the lambda is generated. This is useful for frameworks like Quasar , which uses annotations for concurrency control.
Annotation use-site targets
When you're annotating a property or a primary constructor parameter, there are multiple Java elements which are generated from the corresponding Kotlin element, and therefore multiple possible locations for the annotation in the generated Java bytecode. To specify how exactly the annotation should be generated, use the following syntax:
The same syntax can be used to annotate the entire file. To do this, put an annotation with the target file at the top level of a file, before the package directive or before all imports if the file is in the default package:
If you have multiple annotations with the same target, you can avoid repeating the target by adding brackets after the target and putting all the annotations inside the brackets:
The full list of supported use-site targets is:
property (annotations with this target are not visible to Java)
get (property getter)
set (property setter)
receiver (receiver parameter of an extension function or property)
param (constructor parameter)
setparam (property setter parameter)
delegate (the field storing the delegate instance for a delegated property)
To annotate the receiver parameter of an extension function, use the following syntax:
If you don't specify a use-site target, the target is chosen according to the @Target annotation of the annotation being used. If there are multiple applicable targets, the first applicable target from the following list is used:
Java annotations
Java annotations are 100% compatible with Kotlin:
Since the order of parameters for an annotation written in Java is not defined, you can't use a regular function call syntax for passing the arguments. Instead, you need to use the named argument syntax:
Just like in Java, a special case is the value parameter; its value can be specified without an explicit name:
Arrays as annotation parameters
If the value argument in Java has an array type, it becomes a vararg parameter in Kotlin:
For other arguments that have an array type, you need to use the array literal syntax or arrayOf(...) :
Accessing properties of an annotation instance
Values of an annotation instance are exposed as properties to Kotlin code:
Ability to not generate JVM 1.8+ annotation targets
If a Kotlin annotation has TYPE among its Kotlin targets, the annotation maps to java.lang.annotation.ElementType.TYPE_USE in its list of Java annotation targets. This is just like how the TYPE_PARAMETER Kotlin target maps to the java.lang.annotation.ElementType.TYPE_PARAMETER Java target. This is an issue for Android clients with API levels less than 26, which don't have these targets in the API.
To avoid generating the TYPE_USE and TYPE_PARAMETER annotation targets, use the new compiler argument -Xno-new-java-annotation-targets .
Repeatable annotations
Just like in Java , Kotlin has repeatable annotations, which can be applied to a single code element multiple times. To make your annotation repeatable, mark its declaration with the @kotlin.annotation.Repeatable meta-annotation. This will make it repeatable both in Kotlin and Java. Java repeatable annotations are also supported from the Kotlin side.
The main difference with the scheme used in Java is the absence of a containing annotation , which the Kotlin compiler generates automatically with a predefined name. For an annotation in the example below, it will generate the containing annotation @Tag.Container :
You can set a custom name for a containing annotation by applying the @kotlin.jvm.JvmRepeatable meta-annotation and passing an explicitly declared containing annotation class as an argument:
To extract Kotlin or Java repeatable annotations via reflection, use the KAnnotatedElement.findAnnotations() function.
Learn more about Kotlin repeatable annotations in this KEEP .
List Of All Annotation (Metadata) Programs:
- How to create basic custom annotation?
- What is Retention policy in java annotations?
- How to get annotations at runtime using java reflection?
- How to get all annotations from a class?
- How to assign default values to custom annotations?
- What is marker annotation and how to process it at runtime?
- Built-in Java Annotations: @Deprecated example
- Built-in Java Annotations: @Override example
- Built-in Java Annotations: @SuppressWarnings example
- What is single member annotation and how to process it?
- Java Interview Programs
- Data Structure Programs in Java
- Linked List Programs in Java
- Python Tutorial for Beginners
Java2Novice
About Author
I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.
If you come across any mistakes or bugs, please email me to [email protected] .
Most Visited Pages
- Java Interview Questions
- How to Create Java Custom Exception
- Spring-Boot Tutorial with Examples
- Java Constructor Chaining Examples
- Spring Framework Examples
- Write a program to find maximum repeated words from a file.
- Java Data Structures
- Java 8 new features
- Write a program to find common integers between two sorted arrays.
Other Interesting Sites
- ShortNews247

Java New Features
Java 9 features, java 8 features, java 7 features, java 4/5 features.
Example to specify annoation for a class
Example to specify annotation for a class, methods or fields.
@Retention annotation is used to specify to what level annotation will be available.
Example to specify the RetentionPolicy
Example of custom annotation: creating, applying and accessing annotation.
Let's see the simple example of creating, applying and accessing annotation.
File: Test.java
How built-in annotaions are used in real scenario?
In real scenario, java programmer only need to apply annotation. He/She doesn't need to create and access annotation. Creating and Accessing annotation is performed by the implementation provider. On behalf of the annotation, java compiler or JVM performs some additional operations.
By default, annotations are not inherited to subclasses. The @Inherited annotation marks the annotation to be inherited to subclasses.
@Documented
The @Documented Marks the annotation for inclusion in the documentation.

- Send your Feedback to [email protected]
Help Others, Please Share

Learn Latest Tutorials

Transact-SQL

Reinforcement Learning

R Programming

React Native

Python Design Patterns

Python Pillow

Python Turtle

Preparation

Verbal Ability

Interview Questions

Company Questions
Trending Technologies

Artificial Intelligence

Cloud Computing

Data Science

Machine Learning

B.Tech / MCA

Data Structures

Operating System

Computer Network

Compiler Design

Computer Organization

Discrete Mathematics

Ethical Hacking

Computer Graphics

Software Engineering

Web Technology

Cyber Security

C Programming

Control System

Data Mining

Data Warehouse
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] Duration: 1 week to 2 week


IMAGES
VIDEO
COMMENTS
In the initialize method you can get the values, which are defined in the annotation. The isValid method is used to validate the object (
Meta Annotations · 1. @Retention · 2. @Documented · 3. @Target · 4. @Inherited · 5. @Repeatable.
Overview of Java Built-in Annotations · @FunctionalInterface public interface Adder { int add(int a, int b); } · Adder adder = (a,b) -> a + b; int
Predefined Annotations in java · 1) @Override · 2) @Deprecated · 3) @SuppressWarnings · 4) @Documented Annotations in Java · 5) @Target · 6) @Inherited.
Predefined/ Standard Annotations · Four are imported from java.lang.annotation: @Retention, @Documented, @Target, and @Inherited. · Three are
Predefined Annotation Types ; @Deprecated @Deprecated ; @Override @Override ; @SuppressWarnings @SuppressWarnings ; @SafeVarargs @SafeVarargs ; @FunctionalInterface
lang or java.lang.annotation packages of the Java SE API. In the previous examples, Override and SuppressWarnings are predefined Java annotations. It is
If a Kotlin annotation has TYPE among its Kotlin targets, the annotation maps to java.lang.annotation.ElementType.TYPE_USE in its list of Java
Annotations allows us to add some form of metadata information into our source code, but it doesnot change the execution flow of the program. These annotations
Java Annotations · class Animal{; void eatSomething(){System.out.println("eating something");}; } · import java.util.*; · class A{; void m(){System.out. · @interface
Java 8 adds type annotations. Annotations on all occurrences of types: @Untainted String query;. List<@NonNull String> strings;.