Java Annotations

Annotation is code about the code, that is metadata about the program itself. In other words, organized data about the code, embedded within the code itself. It can be parsed by the compiler, annotation processing tools and can also be made available at run-time too.

We have basic java comments infrastructure using which we add information about the code / logic so that in future, another programmer or the same programmer can understand the code in a better way. Javadoc is an additional step over it, where we add information about the class, methods, variables in the source code. The way we need to add is organized using a syntax. Therefore, we can use a tool and parse those comments and prepare a javadoc document which can be distributed separately.

Javadoc facility gives option for understanding the code in an external way, instead of opening the code the javadoc document can be used separately. IDE benefits using this javadoc as it is able to render information about the code as we develop. Annotations were introduced in JDK 1.5

Uses of Annotations

Annotations are far more powerful than java comments and javadoc comments. One main difference with annotation is it can be carried over to runtime and the other two stops with compilation level. Annotations are not only comments, it brings in new possibilities in terms of automated processing.

In java we have been passing information to compiler for long. For example take serialization, we have the keyword transient to tell that this field is not serializable. Now instead of having such keywords decorating an attribute annotations provide a generic way of adding information to class/method/field/variable. This is information is meant for programmers, automated tools, java compiler and runtime. Transient is a modifier and annotations are also a kind of modifiers.

Ads by Google

More than passing information, we can generate code using these annotations. Take webservices where we need to adhere by the service interface contract. The skeleton can be generated using annotations automatically by a annotation parser. This avoids human errors and decreases development time as always with automation.

Frameworks like Hibernate, Spring, Axis make heavy use of annotations. When a language needs to be made popular one of the best thing to do is support development of frameworks based on the language. Annotation is a good step towards that and will help grow Java.

When Not to Use Annotations

  • Do not over use annotation as it will pollute the code.
  • It is better not to try to change the behaviour of objects using annotations. There is sufficient constructs available in oops and annotation is not a better mechanism to deal with it.
  • We should not what we are parsing. Do not try to over generalize as it may complicate the underlying code. Code is the real program and annotation is meta.
  • Avoid using annotation to specify environment / application / database related information.

Annotation Structure

There are two main components in annotations. First is annotation type and the next is the annotation itself which we use in the code to add meaning. Every annotation belongs to a annotation type.

Annotation Type:

@interface  {
method declaration;

Annotation type is very similar to an interface with little difference.

  • We attach ‘@’ just before interface keyword.
  • Methods will not have parameters.
  • Methods will not have throws clause.
  • Method return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types.
  • We can assign a default value to method.

Meta Annotations

Annotations itself is meta information then what is meta annotations? As you have rightly guessed, it is information about annotation. When we annotate a annotation type then it is called meta annotation. For example, we say that this annotation can be used only for methods.

public @interface MethodInfo { }

Annotation Types

  1. Documented
    When a annotation type is annotated with @Documented then wherever this annotation is used those elements should be documented using Javadoc tool.
  2. Inherited
    This meta annotation denotes that the annotation type can be inherited from super class. When a class is annotated with annotation of type that is annotated with Inherited, then its super class will be queried till a matching annotation is found.
  3. Retention
    This meta annotation denotes the level till which this annotation will be carried. When an annotation type is annotated with meta annotation Retention, RetentionPolicy has three possible values:

    public @interface Developer {
    	String value();
    • Class
      When the annotation value is given as ‘class’ then this annotation will be compiled and included in the class file.
    • Runtime
      The value name itself says, when the retention value is ‘Runtime’ this annotation will be available in JVM at runtime. We can write custom code using reflection package and parse the annotation. I have give an example below.
    • Source
      This annotation will be removed at compile time and will not be available at compiled class.
  4. Target
    This meta annotation says that this annotation type is applicable for only the element (ElementType) listed. Possible values for ElementType are, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE.

    public @interface FieldInfo { }

Built-in Java Annotations

@Documented, @Inherited, @Retention and @Target are the four available meta annotations that are built-in with Java.

Apart from these meta annotations we have the following annotations.


When we want to override a method, we can use this annotation to say to the compiler we are overriding an existing method. If the compiler finds that there is no matching method found in super class then generates a warning. This is not mandatory to use @Override when we override a method. But I have seen Eclipse IDE automatically adding this @Override annotation. Though it is not mandatory, it is considered as a best practice.


When we want to inform the compiler that a method is deprecated we can use this. So, when a method is annotated with @Deprecated and that method is found used in some place, then the compiler generates a warning.


This is like saying, “I know what I am doing, so please shut up!” We want the compiler not to raise any warnings and then we use this annotation.

Custom Annotations

We can create our own annotations and use it. We need to declare a annotation type and then use the respective annotation is java classes.

Following is an example of custom annotation, where this annotation can be used on any element by giving values. Note that I have used @Documented meta-annotation here to say that this annotation should be parsed by javadoc.

 * Describes the team which wrote the code
public @interface Team {
    int    teamId();
    String teamName();
    String teamLead() default "[unassigned]";
    String writeDate();    default "[unimplemented]";

Annotation for the Above Example Type

... a java class ...
    teamId       = 73,
    teamName = "Rambo Mambo",
    teamLead = "Yo Man",
    writeDate     = "3/1/2012"
public static void readCSV(File inputFile) { ... }
... java class continues ...

Marker Annotations

We know what a marker interface is. Marker annotations are similar to marker interfaces, yes they don’t have methods / elements.

 * Code annotated by this team is supreme and need
 * not be unit tested - just for fun!
public @interface SuperTeam { }
... a java class ...
@SuperTeam public static void readCSV(File inputFile) { ... }
... java class continues ...

In the above see how this annotation is used. It will look like one of the modifiers for this method and also note that the parenthesis () from annotation type is omitted. As there are no elements for this annotation, the parenthesis can be optionally omitted.

Single Value Annotations

There is a chance that an annotation can have only one element. In such a case that element should be named value.

 * Developer
public @interface Developer {
    String value();
... a java class ...
public static void readCSV(File inputFile) { ... }
... java class continues ...

How to Parse Annotation

We can use reflection package to read annotations. It is useful when we develop tools to automate a certain process based on annotation.


package com.javapapers.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public @interface Developer {
	String value();
package com.javapapers.annotations;
public class BuildHouse {
	@Developer ("Alice")
	public void aliceMethod() {
		System.out.println("This method is written by Alice");
	@Developer ("Popeye")
	public void buildHouse() {
		System.out.println("This method is written by Popeye");
package com.javapapers.annotations;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class TestAnnotation {
	public static void main(String args[]) throws SecurityException,
			ClassNotFoundException {
		for (Method method : Class.forName(
				"com.javapapers.annotations.BuildHouse").getMethods()) {
			// checks if there is annotation present of the given type Developer
			if (method
					.isAnnotationPresent(com.javapapers.annotations.Developer.class)) {
				try {
					// iterates all the annotations available in the method
					for (Annotation anno : method.getDeclaredAnnotations()) {
						System.out.println("Annotation in Method '" + method
								+ "' : " + anno);
						Developer a = method.getAnnotation(Developer.class);
						if ("Popeye".equals(a.value())) {
							System.out.println("Popeye the sailor man! "
									+ method);
				} catch (Throwable ex) {


Annotation in Method 'public void com.javapapers.annotations.BuildHouse.aliceMethod()' : @com.javapapers.annotations.Developer(value=Alice)
Annotation in Method 'public void com.javapapers.annotations.BuildHouse.buildHouse()' : @com.javapapers.annotations.Developer(value=Popeye)
Popeye the sailor man! public void com.javapapers.annotations.BuildHouse.buildHouse()

apt / javac for Annotation Processing

In previous version of JDK apt was introduced as a tool for annotation processing. Later apt was deprecated and the capabilities are included in javac compiler. javax.annotation.processing and javax.lang.model contains the api for processing.

This Core Java tutorial was added on 03/06/2012.



Comments on “Java Annotations”

  1. Ajai G

    Very well narrated Annotation in detail. Specially to mention the Runtime Reflection example tops it all. Keep going..!!

  2. Mario Guerrero


  3. chandrashekar

    Thaks .It is very useful for me

  4. krishnamurthy

    Nice one Joe.It is very use full to me.

  5. chandoo

    Joe, you are Excellent……….

  6. Praveen Kumar Jayaram

    Nice article.

  7. S.Narayana Moorthi


    It was a great surprise to me seeing ur blog. Your learning is great!
    Your attitude to share it is greater!
    Sharing it in a way even a layman would understand is the greatest of all!
    Keep rocking. :)

  8. Anonymous

    Cool stuff..great refresher ..


  9. Suvasish

    really great!!!! keep up doing the good work for us..

  10. Satheskumar

    Hi Joe. The things posted here are very much useful to everyone. Thanks..

  11. Moove

    How abt including the Like button in the end of article…??

  12. Anonymous

    Nice post Joe!

  13. krishnamurthy

    Good example Joe…..

  14. Kapil Suryawanshi

    Fantastic information. I didnt know what was this concept, but now I am comfortable to play with it.
    Thank you.

  15. sara

    great, keep going

  16. it’s amazing u r blog.I am first watch this blog it was good. wondonful

  17. swapnil gorane

    gr8 , thank you,
    it is very help full for me…

  18. Given inDetailed Annotation explanations. Very very Thanks.

  19. Vysakh Suresh

    Thank you . . ;)

  20. Jawahar

    Very nice one Joe! Thank you very much

  21. Gootam

    Good Work Joe.. Please keep it up

  22. Kiran

    Good Work Joe… Want to know some more information like how the injection happens in webservices when a “@WebServiceRef” annotation is used.

  23. Kiran

    Using Reflection only?

  24. Rakesh Kunwar

    nice page…………

  25. Kumar

    Good Article.Keep Going

  26. shiva

    with example

  27. shiva

    sorry its inherited

  28. Rajeev

    Very good Article. It gives us complete understanding about the Annotations.


  29. Anonymous

    Its very useful for the newbies like me :-)

  30. Sajjan

    Very nicely compiled article. You should write tech books :) Thanks.

  31. Giri Kanchukota

    Nice information to learn annotations

  32. Jicky

    multivalue annotation is not exmplained

  33. Thanks. It’s very helpful for me after all searching through google, finally i got good note.

  34. Saurabh Prakash

    Great Stuff.Thanks

  35. jvmlover

    Pretty good article!
    Keep going, your blog is great.

  36. Rajesh

    Simple and Super!!

  37. Durgasankar

    Good One Joe keep going……….

  38. Ajay K

    HI Joe, I found this article interesting, but somehow it seems good only for beginers. The part which i felt missing was much more technical part to the actual topic, which i found same in link:


  39. Gilsha

    Great stuff Joe. Thanks

  40. Karunanidhi

    Good introduction on annotations exactly what I looked for.

  41. vijay

    Dear Joe, I am a newbie and I have become your fan. Whenever I google for some topics in Java and I see your picture, I go straight for your link.

    You explanations are simple and straight forward. Please keep up the good work.

    And thanks again!

  42. Rahul Raj

    Mast Narrated Explanation bhai

  43. Mubarak Ali

    Good work. Thanks.

  44. pooja

    Hi Joe – i have read almost all your articles..u explain every concept so well.. keep it up :)

    I have one very basic question for Annotation. I have googled this at so many places but not got satisfactory ans.

    Just i want to know
    b) Annotation is for JVM or for compiler or for other tools.
    c)If it is for some specific tool, where i define it.

    For eg i created any class for caching purpose and i made annotation for it like cacheable.. but what use of doing it.. M i really achieving anything?

    My question might sounds you little too basic or dumb but would appreciate if you will answer.

    Thanks in advance

  45. Very Cool and illustrative tutorial .. i enjoyed a lot here , Sir keep it up…

  46. Shiv

    Joe you have mentioned that don’t use annotations for data base related things, but in hibernate annotations are used for mapping.

    Can you clarify my confusion?

  47. Subin

    Excellent explaination, you are awesome

  48. sachin

    very simple and precise explanation. thanks a lot…

  49. MD AMIN

    Really very useful………….

  50. sivam

    Excellent Thaliava

  51. Thennam

    Hi Joe,

    Thanks for the wonderful information on annotations.

    It will be really helpful, if you provide the followings

    1. Advantage of annotations? How annotations helps the developers?

    2. When should we go for annotations?

    3. How the annotations affects the behavior of the class @ run-time? if yes, please explain.

  52. Purush

    Hi Joe, Thanks for the nice explanation about basics on Annotation.

    Can you please clarify… is it possible to pass as annotation as Parameter to a method


  53. Udhay

    Why do we go for annotations? for ex: @Inherited used for inherit the super class to derived class. that can be done through the ‘extends keyword’ right?, then what is the need of Annotaions?

  54. Srinivas

    Hi, is there a way to remove annotation of a class runtime ?

  55. Nandish

    Thanks for that wonderful tutorial

  56. sanu


  57. kasinathan

    i didn’t get the clear idea about the @inherited

    i want more explanation

    For Example @Test class it has been inherit the properties of the class Test.How can i do that one.I need a One Example
    Thanks …..

  58. Anonymous

    Please write a tutorial on Spring annotations..

  59. Dev

    thanks a lot

  60. Anonymous

    I am not undestanding clearly.
    I want more explanation about annotations.

  61. Anonymous

    This is Suresh Arkati..
    Than q for u r Material….

  62. GopiNaidu

    Excellent Joe, It is very useful. Thanks

  63. Rajesh Antony

    Great work Joe. This was an elusive topic but your narration hugged me to the topic and made me confident. Your Great attitude to share is appreciated.

  64. Karthik M

    Thanks for the good tutorial

  65. Karan D Singh

    Beautiful Explanation.. Immaculate.

      • Anonymous

        teamId = 73,
        teamName = “Rambo Mambo”,
        teamLead = “Yo Man”,
        writeDate = “3/1/2012″

        in this case we will see same code in generated javadoc. I mean
        @Team(teamId=73,teamName=”Rambo Mambo”,…

        Is anyone knows how to put only values in javadoc. For exaple
        public @interface MyAnnotation {
        String description() default “none”;
        I need to put ONLY! String value of description.

  66. sal

    can i create an annotation where i can use the logger



    class Test{“this is test method”);


    means i want to just add @Logger above the class,it will use the respective class name and LOGGER instance.

    how can i do the same



  67. Anonymous

    i m out of this field, bt i think sharing s so good, thanks,keep going!!!!

  68. rajib


  69. csk

    explanation was good…

  70. Loveleen Girdhar

    sir i m new in industry and in which company i m there is work of springs,hibernate. can u plz tell me from where should i read these things…

    Thanks in advance.

  71. Nitin

    good explanation !
    Tell me advantages and why should we use ?

  72. Abhay

    But what is the effect the Annotation can have on the method . i.e how the method is associated with Annotation.

    @interface myAnnotation1{
    public String name() default “Abhay”;
    public int age() default 35;


    class Annotated {

    public void foo(String myParam) {

    System.out.println(“This is ” + myParam);

    What effect the @myAnnotation is having on foo() and how can we access the values of @myAnnotation in foo() method..

  73. Elangovan

    Really useful. I appreciate your hard work to make people understand java easily. Keep it up.

  74. Yatheesh

    gud one. Thankq

  75. Saidi

    Your blog has been very userful

  76. Shaffic

    Hi Joe,

    Thanks for giving glimpse on annotations :)

  77. mandee

    The explanation on the topic here is the best as compared to other blogs. I would appreciate if you could explain “How to Parse Annotation” a bit more so that even a beginner can understand (actually i couldn’t understand what’s going on in the code).


  78. Abhishek

    Hi Joe ,

    What i a trying to do is that

    Step 3: Create Axis2 Web Service

    I am trying to keep the server runtime and web services runtime same.
    As i dont have the axis client with me right now.

    I am using jboss for the same.
    for this purpose i have created there are two jboss folders i.e. one is the jboss and another is copy of it.

    I have given different paths for the server runtime and web server runtime.

    server runtime —-path of the jboss folder
    web server runtime —path of the copy of the jboss folder

    Now the issue is
    —>when i click on the next button
    —>check the option as Generate wsdl file
    —->and then again click on the next button.

    the error which i am getting is system can not find the path specified.

    I am still puzzled, which path the system is looking for.

    Can you pls guide.

    Abhishek J

  79. Sagar Deshmukh

    Nice explanation!
    One quick question.
    What if I want to have dynamic argument value in argument

    public @interface Developer {
    String merID();
    package com.javapapers.annotations;
    public class BuildHouse {

    @Developer (merID = merID)
    public void aliceMethod(String merID) {
    System.out.println(“This method is written by Alice”);


    here I want to set that argument ‘merID’ value to be the same as value of argument I’m passing in method ‘aliceMethod(String merID)’.

  80. Pooja

    really helpful .. great work done

    by explaining so neatly .. thank U

  81. Pooja

    really helpful .. great work done

    by explaining so neatly .. thank U

  82. Enrico

    Very nice explanation. Good Work! Tks

  83. jaiganesh

    I believe that we can create annotations with Retention Policy SOURCE (or) CLASS.

    But I could not imagine the real time scenarios. If Retention Policy is CLASS, how can I instruct compiler to do particular task?
    If it’s SOURCE, can we create some applications like javadoc ?

  84. sandeep

    What is most important widely used design pattern in java?
    can u briefly explain? What is Observer design pattern?

  85. Explain Java

    Very clean explanation. Keep it up :)

  86. kabeer

    Hi , Great post
    Can you please tell how we can invoke methods also ,so that will get an idea how exactly JUnit ,TestNG
    If I am not wrong these tools work on Reflection and Annotation ?

  87. Soumen Goswami

    Great discussion. Very Helpful. Thank You

  88. moni

    anyone help me to know how to define values while creating annotation and how to call and compare that values in annotation

  89. Arun

    Very Nice article… Helpful to understand Annotations.

  90. sanchit

    very well organised tutorial, thanks

  91. A Ray

    Replace ‘Annotation Types’ with ‘Meta Annotation Types’ in the heading under the ‘Meta Annotation’ section. Very well written nevertheless. Keep up the good work ! Appreciate it !

  92. Anonymous

    thanks Joe

  93. Adil Jdidi

    Very nice and simple example. thank you

  94. Karthikeyeni K

    Very well explained. Thanks. Keep the good job.

  95. Sakthivel

    appreciate your passion!

    Sharing knowledge is more than sharing wealth!!

    Good luck to u always

    “Be a good person, and need not prove it”

  96. Thanks Joe Sir……..u always help me out whnever i stuck at any point……..

  97. Ramesh Pasham

    I like your simple narration which gives more clarity on topic.
    Super Joe :-)

  98. Arun K

    Hi Joe,

    All your articles are easy to understand. Thanks for such a explanation. I suggest you to describe further in detail where ever required.

    My question to you is:

    step 1) I have created Customize annotation

    public @interface ExecuteBeforeMethod{
    //Some attributes over here
    String methodName();
    String className();

    step 2) Creat Class where i use above annotation

    Class Test{
    @ExecuteBeforeMethod(className=”xyz”, methodName=”abc”)
    public method(){

    //Some logic over here

    But how does JVM comes to know at runtime to call method which i mentioned in my annotation? or How does dynamic binding of annotation and for method to which i written annotation is related to?

    Parsing i know and you written it in main() method in your example.

    But for my application how do i do?

    When my code call “method()” before that how method which i mentioned in annotation is called? or How and where parser is linked in this case?

  99. Vairavel


  100. Venkat

    Nice Stuff

  101. anushri nayak

    Good one :)

  102. Venu

    Good Stuff …………

  103. saravanan

    Superb explanation….thanks

  104. papiya

    ‘If the compiler finds that there is no matching method found in super class then generates a warning.’

    Please verify the above line under @Override.
    I think it creates compilation error…

    Anyways thanks for writing the blog.It was helpful.

  105. Anonymous


    Its really good, after red this i impressed a lot, Thank you Joe for this Tremendous effort. Keep it up

  106. Subhadeep Ray

    Rambo Mambo was good.

  107. KAILASH

    Dear Joe,

    First of all thanks for the article.It’s really very useful. However i have one query. Are you sure that we can’t use parameters in methods?

    Because i have seen methods like following

    public String Joe(@RequestParam(“name”) String name, Model model)
    String message = “Hi” + name + “!”;
    model.addAttribute(“message”, message);
    return “Joe” ;

  108. Satish

    Hi Joe,

    First of all thanks a lot for presenting annotations in detail. It’s quite helpful

    But one thing I am very much eager to know is,

    Will it cause any issue if the annotations got compiled with one version of jdk (say jdk1.5) and the classes that use these annotations are complied with a different version of jdk (say jdk1.7) ?

  109. Vijayagopal

    Very good presentation, go ahead….

  110. Joseph Kingston Leo M

    Thanks for Annotation KISS.(Keep it simple sir)

  111. Preeti Gupta

    Very informative, simple and easy to understand tutorial.. great work.. Keep it up joe..

  112. Piyush

    I enjoyed this reading . Thank you.

  113. Anonymous

    Thankyou Joe

  114. ajit

    Keep up the good work!

  115. neila

    It s instructive

  116. Bhagat

    it was an awesome experience to learn java form here
    keep it up!!!!

  117. Jeet

    it’s good explanation.

  118. Avinash Babu Donthu

    Thank you Joe. This is very helpful

  119. Bharat D

    great work…..

  120. Anonymous


  121. Amir

    good and clear explanation… Would be great if Joe can answer the questions posted by viewers on the comments. I know it needs moretime, but found many unanswered.

  122. Anonymous

    Awesome explanation

  123. Anonymous

    really nice one..thanks so much.

  124. srikanth

    needs to be covered all the possible topics, it was just like a introduction

  125. Michael Vino

    Such a wounderful articale

  126. kumar

    How can i get the field name while creating our own annotation?

  127. rajesh kumar mallick

    This is very clear and good presentative.somany things i got it aboput annotaion.

  128. Siddique

    Sir, We want annotation list .

  129. Siddique

    Please can you provide the annotation list on this email id..

    Thanking you

  130. Suresh

    Nice post…

  131. Anonymous

    Nice description. Please continue the gud work.

  132. harish

    which of the following is an example of Marker Annotation?

    which of the following is an example of Multi value annotation?

  133. harish

    which of the following keyword is used to create an user defined annotation?
    d)NOne of the above

    which of the following is used only in the case of Inheritance?
    a) @Depricated

  134. ramachandrareddy

    what is usages in real time senariao of annations

Your Comment