Home Ejb Annotations
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Annotations

Advertisement
Sun Microsystem added the features like annotation to make the development easier and more efficient in jdk 5. The main objective to develop the annotations is to make the development easier.

Annotations

     

Sun Microsystem added the features like annotation to make the development easier and more efficient in jdk 5. The main objective to develop the annotations is to make the development easier. Annotations behaves like the meta. The literal meaning of meta data is data about data. Java also signifies this meaning. Annotations are like meta data, means you are free to add your code and can also apply them to variables, parameters, fields type declarations, methods and constructors. Metadata is also used to create the documentation to perform rudimentary compile time checking and even for tracking down the dependencies in code. XDoclet contains all these features and is widely used. Annotations provide a means of indicating about methods, classes, dependencies, incompleteness and also about the references on other methods and classes respectively. Quoting from Sun's official site, "It (annotation-based development) lets us avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a declarative programming style where the programmer says what should be done and tools emit the code to do it." 

Annotation is the way of associating the program elements with the meta tags so that the compiler can extract program behavior to support the annotated elements to generate interdependent code when necessary.

Fundamentals of annotations

While going through the annotations you should consider two things. The first one is the "annotation" itself and second one is the "annotations types". An annotation is the meta tag, used to give some life to the code you are using. While annotation type is used to define annotations so that you can use them while creating your own custom annotations.

An annotation type definition appends an "at" @ sign at the start of the interface keyword with the annotation name. On the other hand, an annotation includes the "at" @ sign followed by the annotation type. You can also add the data within the parenthesis after the annotation name. Lets illustrate the concept more clearly by using some examples.

Defining an annotation (Annotation type)

public @interface Example {
String showSomething();
}

Annotating the code (Annotation)

Example (showSomething="Hi! How r you")
public void anymethod() {
....
}

Annotation Types: Three types of annotations types are there in java.

  • Marker: Like the marker interface, marker annotations does not contain any elements except the name itself. The example given below clarifies the concept of marker interface.

   Example:

   public @interface Example{

   }

  Usage:

  @Example
   public void anymethod() {
  ------------
   }

  • Single-value: This type of elements provide only single value. It means that these can be represented with the data and value pair or we can use the shortcut syntax (just by using the value only within the parenthesis).

  Example: 

  public @interface Example{

  String showSomething();

   }

  Usage: 

   @Example ("Hi ! How r you")
   public void anymethod(){

   --------

   }

  • Multi-value or Full-value: These types of annotations can have multiple data members. Therefore use full value annotations to pass the values to all the data members.

  Example:

  public @interface Example{

  String showSomething();
  int num; 
  String name;

   }

  Usage: 

  @Example (showSomething = "Hi! How r you", num=5, name="zulfiqar" )
   public void anymethod{

   // code here

   }

Rules defining the Annotation type: Here are some rules that one should follow while defining and using annotations types

  • Start the annotation declaration starting with the symbol "at" @ following the interface keyword that should follow the annotation name.
  • Method declaration should not throw any exception.
  • Method declaration should not contain any parameter.
  • Method using annotations should return a value, one of the types given below:
  • String 
  • primitive
  • enum
  • Class
  • array of the above types

Annotations: JDK 5 (Tiger) contains two types of annotations:

  • Simple annotations: These types of annotations are used to annotate the code only. We can not use these types of annotations for creating the custom annotation type.
  • Meta annotations: Also known as annotations of annotations are used to annotate the annotation-type declaration.

Simple annotations: JDK 5 includes three types of simple annotations.

  • Override
  • Depricated
  • Suppresswarnings

JDK 5 (also known as Tiger) does not include many built-in annotations but it facilitates to core java to support annotation features. Now will discuss in brief each of the above simple annotation types along with examples.

Override annotation: The override annotation ensures that the annotated method is used to override the method in the super class. If the method containing this type of  annotation does not override the method in the super class then the compiler will generate a compile time error. 

Lets take an example and demonstrate what will happen if the annotated method does not override the method in the super class.

Example 1: 

public class Override_method{
@Override
public String toString(){
return super.toString() + 
  "Will generate an compile time error.";
}
}

Suppose there is spell mistake in the method name such as the name is changed from toString to toStrimg. Then on compiling the code will generate the message like this:

Compiling 1 source file to D:tempNew Folder (2)
TestJavaApplication1buildclasses
D:tempNew Folder (2)TestJavaApplication1srctest
myannotationTest_Override.java:24: method does not override
a method from its superclass
@Override
1 error
BUILD FAILED (total time: 0 seconds)

Deprecated annotation: These types of annotations ensure that the compiler warns you when you use the deprecated element of the program. The example given below illustrates this concept.

Example: Lets first create the class containing the deprecated method.

public class Deprecated_method{
@Deprecated
public void showSomething() {
System.out.println("Method has been depricated'");
}
}

Now lets try to invoke this method from inside the other class:

public class Test_Deprication {
public static void main(String arg[]) throws Exception {
new Test_Deprication(); 
}
public Test_Deprication() {
Deprecated_method d = new Deprecated_method();
d.showSomething();
}

The method showSomething() in the above example is declared as the deprecated method. That means we can't further use this method any more. On compiling the class Depricated_method does not generate any error. While compiling the class Test_Deprication generates the message like this:

Compiling 1 source file to D:tempNew Folder
(2)TestJavaApplication1buildclasses
D:tempNew Folder
(2)TestJavaApplication1srctestmyannotation
Test_Deprication.java:27:
warning: [deprecation] showSomething() in
test.myannotation.Deprecated_method has been deprecated
d.showSomething();
1 warning

The Suppresswarning annotation: These types of annotations ensure that the compiler will shield the warning message in the annotated elements and also in all of its sub-elements. Lets take an example:

Suppose you annotate a class to suppress a warning and one of its method to suppress another warning, then both the warning will be suppressed at the method level only. Lets demonstrate it by an example:

public class Test_Depricated {
public static void main(String arg[]) throws Exception {
new TestDepricated().showSomething();
}
@SuppressWarnings({"deprecation"})
public void showSomething() {
Deprecation_method d = new Deprecation_method();
d.showSomething();
}
}

This example is suppressing the deprecation warnings that means we can't see the warnings any more.

Note: Applying annotation at most deeply nested elements is a good idea. It is better to apply annotations at the method level rather than the class to annotate a particular method.

Meta-Annotations (Annotation Types): There are four types ofm Meta annotations (or annotations of annotations) defined by the JDK 5. These are as follows:

  • Target
  • Retention
  • Documented
  • Inherited

Target annotation: Target annotation specifies the elements of a class to which annotation is to be applied. Here is the listing of the elements of the enumerated types as its value:

  • @Target(ElementType.TYPE)?applicable to any element of a class.
  • @Target(ElementType.FIELD)?applicable to field or property.
  • @Target(ElementType.PARAMETER)?applicable to the parameters of a method.
  • @Target(ElementType.LOCAL_VARIABLE)?applicable to local variables.
  • @Target(ElementType.METHOD)?applicable to method level annotation.
  • @Target(ElementType.CONSTRUCTOR)?applicable to constructors.
  • @Target(ElementType.ANNOTATION_TYPE)?specifies that the declared type itself is an annotation type.

Here is an example that demonstrates the target annotation:

Example:

@Target(ElementType.METHOD)
public @interface Test_Element {
public String doTestElement();
}

Now lets create a class that use the Test_Element annotation:

public class Test_Annotations {
public static void main(String arg[]) {
new Test_Annotations().doTestElement();
}
@Test_Target(doTestElement="Hi ! How r you")
public void doTestElement() {
System.out.printf("Testing Target Element annotation");
}
}

The @Target(ElementType.METHOD) specifies that this type of annotation can be applied only at method level. Compiling and running the above program will work properly. Lets try to apply this type of annotation to annotate an element:

public class Test_Annotations {
@Test_Target(doTestElement="Hi! How r you")
private String str;
public static void main(String arg[]) {
new Test_Annotations().doTestElement();
}
public void doTestElement() {
System.out.printf("Testing Target Element annotation");
}
}

Here we are trying to apply @Target(ElementType.METHOD) at the field level by declaring the element private String str; after the @Test_Target(doTestElement="Hi ! How r you") statement. On compiling this code will generate an error like this:

"Test_Annotations.java": 
D:R_AND_DTest_Annotationsrctestmyannotation
Test_Annotations.java:16: 
annotation type not applicable to this kind of declaration at line
16, column 0
@Test_Target(doTestElement="Hi ! How r you")
^
Error in javac compilation

Retention annotation: These types of annotation specify where and how long annotation with this types are to be retained. There are three type of Retention annotations are of three types.

  • RetentionPolicy.SOURCE: This type of annotation will be retained only at source level and the compiler will ignore them.
  • RetentionPolicy.CLASS: This type of annotation will be retained at the compile time the virtual machine (VM) will ignore them.
  • RetentionPolicy.RUNTIME: Virtual machine will retained the annotation of this type and they can be read only at run-time.

Lets demonstrate that how this type of annotations are applied by taking an example using RetentionPolicy.RUNTIME.

Example:

@Retention(RetentionPolicy.RUNTIME)
public @interface Retention_Demo {
String doRetentionDemo();
}

This example uses the annotation type @Retention(RetentionPolicy.RUNTIME) that indicates the VM will retained your Retention_Demo annotation so that it can be read effectively at run-time.

Documented annotation: This type of annotation should be documented by the javadoc tool. javadoc does not include the annotation by default. Include the annotation type information by using @Documented in the generated document. In this type of annotation all the processing is done by javadoc-like tool.

The given example demonstrates the use of the @Documented annotations.

Example: 

@Documented
public @interface Documented_Demo {
String doTestDocumentedDemo();
}

Next, make changes in Test_Annotations class as follows:

public class Test_Annotations {
public static void main(String arg[]) {
new Test_Annotations().doTestRetentionDemo();
new Test_Annotations().doTestDocumentedDemo();
}
@Retention_Demo (doTestRetentionDemo="Hello retention annotation")
public void doTestRetentionDemo() {
System.out.printf("Testing 'Retention' annotation");
}
@Documented_Demo (doTestDocumentedDemo="Hello Test documentation")
public void doTestDocumentedDemo() {
System.out.printf("Testing 'Documented' annotation");
}
}

Inherited Annotation: This annotation is little bit complex. It inherits the annotated class automatically. If you specify @Inherited tag before defining a class then apply the annotation at your class and finally extend the class then the child class inherits the properties of the parent class automatically. Lets demonstrate the benefits of using the @Inherited tag by an example:  

Example:

Lets first, define the annotation:

@Inherited
public @interface ParentObjectDemo { 
boolean isInherited() default true;
String showSomething() default "Show anything?";
}

Now, annotate the class with our annotation:

@ParentObjectDemo
public Class ChildObjectDemo {
}

The above example shows that you do not need to define the interface methods inside the implemented class. The @Inherited tag automatically inherits the methods for you. Suppose you define the implementing class in the old-fashioned-java-style then let us see the effect of doing this:

public class ChildObjectDemo implements ParentObjectDemo {
public boolean isInherited() {
return false;
}
public String showSomething() {
return "";
}
public boolean equals(Object obj) {
return false;
}
public int hashCode() {
return 0;
}
public String toString() {
return "";
}
public Class annotationType() {
return null;
}
}

Have you seen the difference? You have to implement all the methods of the parent interface. You will have to implement the equals(), toString(), and the hashCode() methods of the Object class and also the annotation type method of the java.lang.annotation.Annotation class. You will also have to include all these methods in your class regardless of whether you are implementing all these methods or not.

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 27, 2008

Ask Questions?    Discuss: Annotations   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
krishna
January 30, 2013
Error or something Missing

@Target(ElementType.METHOD) public @interface Test_Element { // Here u define Test_Element but using Test_Element @Test_Target(doTestElement="Hi ! How r you")// But Using Test_Target how ...i want to know that plz public void doTestElement() { System.out.printf("Testing Target Element annotation"); } }
Hans
July 30, 2012
Errors on page

Hi, to learn a subject it would be helpful if there were no errors in the text (even if they are typos)! 1. Missing @-sign: Defining an annotation (Annotation type) public @interface Example { String showSomething(); } Annotating the code (Annotation) ---> here <--- Example (showSomething="Hi! How r you") public void anymethod() { .... } 2. Wrong annotation name: @Target(ElementType.METHOD) public @interface Test_Element { public String doTestElement(); } Now lets create a class that use the Test_Element annotation: public class Test_Annotations { public static void main(String arg[]) { new Test_Annotations().doTestElement(); } ---> here @Test_Target <--- (doTestElement="Hi ! How r you") public void doTestElement() { System.out.printf("Testing Target Element annotation"); } } I just stopped reading here because I didn't trust the text anymore...
Kate
September 19, 2012
typo

Hi, at the "Target annotation" example, shouldn't use @Test_Element instead of @Test_Target at class Test_Annotations? Regards, Kate Like this: ... public class Test_Annotations { ... @Test_Element(doTestElement="Hi ! How r you") public void doTestElement() { System.out.printf("Testing Target Element annotation"); } }
DMCA.com