Java Annotations: Concepts, Methods and Examples

14 July, 2008 at 14:15 4 comments

An annotation, in the Java computer programming language, is a special form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Unlike Javadoc tags, Java annotations are reflective in that they are embedded in class files generated by the compiler and may be retained by the Java VM to be made retrievable at run-time.

Annotations are a metaprogramming facility introduced J2SE 5.0. They allow us to mark code with defined tags. Some developers think that the Java compiler understands the tag and work accordingly. This is not right. The tags actually have no meaning to the Java compiler or runtime itself. There are tools that can interpret these tags. For instance: IDEs, testing tools, profiling tools, and code-generation tools understands these tags.

Why use annotations?

Metadata is beneficial for documentation, compiler checking, and code analysis.
One can use metadata to indicate if methods are dependent on other methods, if they are incomplete, if a certain class must reference another class, and so on. You might be thinking that this can also be done using Javadoc since it provides a fairly easy and robust way to document code. Yes, this is correct but the truth is, there are other benefits associated with metadata.

Metadata is used by the compiler to perform some basic compile-time checking. For example there is a override annotation that lets you specify that a method overrides another method from a superclass. At this, the Java compiler will ensure that the behavior you indicate in your metadata actually happens at a code level as well. This might seem trivial to you but the fact is that many developers have spent long nights trying to discover why their code is not working and later realizing that a method has a parameter wrong, which means that the method is not overriding a method from a superclass.
Another great feature of using annotation is code analysis. A good tool like XDoclet can manage all of these dependencies, ensuring that classes that have no code-level connection, but do have a logic-level tie-in, stay in sync. In this case, metadata is really useful.

Categories of annotations

There are three categories of annotations:

Marker annotations

There annotations have no variables. These are identified by name, with no additional data supplied. For example:

Code:
@SingleValueAnnotation

Single-value annotations

These are similar to markers, but also provide a single piece of data. You can only provide a single bit of data with these. For example:

Code:
@SingleValueAnnotation(“my data”)

Full annotations

There have multiple data members. Annotations of this type won’t look quite so much like a normal Java method:

Code:
@FullAnnotation(var1="data value 1", var2="data value 2", var3="data value 3")

In addition to supplying values to annotations through the default syntax, you can use name-value pairs when you need to pass in more than one value. You can also supply arrays of values to annotation variables, through curly braces. Following snippet shows an array of values in an annotation.

Code:
@TODOItems({ // Curly braces indicate an array of values is being supplied @TODO( severity=TODO.CRITICAL, item="Add functionality to calculate the mean of the student's grades", assignedTo="Brett McLaughlin" ), @TODO( severity=TODO.IMPOTANT, item="Print usage message to screen if no command-line flags specified", assignedTo="Brett McLaughlin" ), @TODO( severity=TODO.LOW, item="Roll a new website page with this class's new features", assignedTo="Jason Hunter" ) })

The above example might look complex to you, but it’s rather simple. Let me explain it.

TODOItems and TODO are custom annotations. The TODOItems annotation type has a single variable that takes a value. Thing to note is that the single value is an array which contains three TODO annotations.

TODO annotation is multivalued annotation and commas separates the values within each annotation. Also comma is used to separate the value within a single array.

The Basics

There are two things you need to consider with annotations. One is the “annotation” itself; another is the “annotation type.” An annotation is the meta-tag that you will use in your code to give it some life. Annotation type is used for defining an annotation. You will use it when you want to create your own custom annotation. The type is the actual construct used, and the annotation is the specific usage of that type.

An annotation type definition takes an “at” (@) sign, followed by the interface keyword plus the annotation name. On the other hand, an annotation takes the form of an “at” sign (@), followed by the annotation type. This is simplest form of annotation. Additionally, you can put data within parenthesis after the annotation name. An example of each can be seen below:

Example to Define an Annotation (Annotation type)

public @interface MyAnnotation {
   String doSomething();
}

Example to Annotate Your Code (Annotation)

MyAnnotation (doSomething="What to do")
public void mymethod() {
   ....
}

Annotation Types

There are three annotation types:

  • Marker: Marker type annotations have no elements, except the annotation name itself.Example:
    public @interface MyAnnotation {
    }

    Usage:

    @MyAnnotation
    public void mymethod() {
       ....
    }
  • Single-Element: Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis. Example:
    public @interface MyAnnotation
    {
        String doSomething();
    }

    Usage:

    @MyAnnotation ("What to do")
    public void mymethod() {
       ....
    }
  • Full-value or multi-value: Full-value type annotations have multiple data members. Therefore, you must use a full data=value parameter syntax for each member. Example:
    public @interface MyAnnotation {
       String doSomething();
       int count; String date();
    }

    Usage:

    @MyAnnotation (doSomething="What to do", count=1,
                   date="09-09-2005")
    public void mymethod() {
       ....
    }

Simple Annotations

There are only three types of simple annotations provided by JDK5. They are:

  • Override
  • Deprecated
  • Suppresswarnings

It’s important to note that JDK5 (in other words, Tiger) actually does not have many built-in annotations; rather, it allows core Java the ability to support the annotation feature. The charter for JSR-175 strictly dictated it was to define a metadata facility. It was left to the programmers to write custom annotation types and to other JSRs to write a set of standard annotation types. The following sections will describe each simple annotation in more depth, along with examples.

The Override annotation

An override annotation indicates that the annotated method is required to override a method in a super class. If a method with this annotation does not override its super-class’s method, the compiler will generate an error. Example 1 demonstrates the override annotation:

Example 1

public class Test_Override {
@Override
public String toString() {
   return super.toString() +
   " Testing annotation name: 'Override'";
}
}
more

The Deprecated annotation

This annotation indicates that when a deprecated program element is used, the compiler should warn you about it. Example 2 shows you the deprecated annotation.

Example 2

First, create a class with the deprecated method as follows:

public class Test_Deprecated { @Deprecated public void doSomething() { System.out.println(“Testing annotation name: ‘Deprecated'”); } }

more

The Suppresswarnings annotation

This annotation indicates that compiler warnings should be shielded in the annotated element and all of its sub-elements. The set of warnings suppressed in an element is the superset of the warnings in all of its containing sub-elements. As an example, if you annotate a class to suppress one warning and one of its methods to suppress another warning, both warnings will be suppressed at the method level only. See Example 3 for the suppresswarnings annotation.

Example 3

public class TestAnnotations {
   public static void main(String arg[]) throws Exception {
      new TestAnnotations().doSomeTestNow();
   }
   @SuppressWarnings({"deprecation"})
   public void doSomeTestNow() {
      Test_Deprecated t2 = new Test_Deprecated();
      t2.doSomething();
   }
}

more

Meta-Annotations (Annotation Types)

Meta-annotations, which are actually known as the annotations of annotations, contain four types. These are:

  • Target
  • Retention
  • Documented
  • Inherited

for mor information Click here

[http://www.developer.com]

[http://www.java-forums.org]

[wikipedia.org]


Bookmark and Share

Advertisements

Entry filed under: Annotation, Hibernate, Java, JEE. Tags: , .

Unit Testing: Examples, Concepts and Frameworks XQuery: query collections of XML data

4 Comments Add your own

  • 1. Farhaan KAzi  |  27 May, 2010 at 18:52

    Sir,

    I want to know that how to create and initialize array memeber in annotation definition.

    Reply
  • 2. DineshT  |  27 July, 2010 at 07:11

    1) Is the annotation types created in a seperate file as lilke of the interface?
    2) How to add or import the annotations to a particular class?

    Thanks in advance

    Reply
    • 3. Rakesh  |  29 November, 2011 at 04:53

      your answers :

      1) Yes, you can create the annotation types in separate file as interfaces

      2) Annotations are like interfaces you can import them as normal interfaces.

      Reply
  • 4. Noyel  |  16 December, 2010 at 11:16

    Good One!
    Thanks 🙂

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


IT Passion’s Store

Archives

Communities

Get the Source
OSGi supporter
JUG Milano

Upcoming Events



....

Blog Stats

  • 348,048 hits

My PageRank

What's My Google PageRank?

%d bloggers like this: