Member-only story

How well do you actually understand Annotations in Java?

Adrian D. Finlay
9 min readOct 22, 2017

--

Link:Homer Simpson

If you are a web or enterprise developer, which most java developers are, you consume annotations all the time. Whether in Spring, JEE, or Struts, you see them a lot. If you make use of unit testing tools like JUnit the same applies. If you do thick client or Android development, you may not see it as often in actual production code but rather your encounters with them will probably be with production tools, build tools, and testing. If you make use of Contexts & Dependency Injection then annotations are your mainstay.

Sure, you consume them. But do you know how to do basic things like how to define one? Maybe you do. But in my estimation, for the most part, if you are not developing APIs or deployment tools, you may rarely need to define an annotation. I think Annotations are the Java language element that is more commonly not fully understood. Maybe I’m wrong, but that’s just my opinion. Why don’t we start here.

Basic Annotation definition

Notice the syntax of the annotation definition with ‘@interface’ denoting the type. This is how the compiler recognizes an annotation type. This syntax is because Annotation types are based off of the same plumbing behind the interface. Also notice the method declarations. You don’t implement these as you would do in a normal interface. The compiler does. Also, the methods() are (for all concern to the applications developer) treated like fields when using them. Notice Ln. 8. We simply say age = 33 as if age were a ordinary member and not a method.

Although it is not obvious from the source code, the annotation used on Ln. 8 leaves the program unchanged. Recall that annotations are merely metadata, they do not change the nature of a program (at least not directly). Annotations, can signal to development tools to do a certain action based on the type of annotation. One good example of this is the CDI Engine of Java EE. What then happens as a consequence is that the CDI run-time provides X based on X annotation but the actual source file itself, still, does not change.

Restrictions on Annotation Types [1]

  • Annotations cannot participate in inheritance.
  • Annotations methods may not have arguments.

--

--

Adrian D. Finlay
Adrian D. Finlay

Written by Adrian D. Finlay

@thewiprogrammer. Lover of learning, programming. Tech writer, Java aficionado. Proud mango, fishing, NBA addict! & more. Network w/ me @ bit.ly/AdfNtWk

Responses (4)