7:33 am - Monday November 19, 2018

Annotations in java

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

ANNOTATIONS

Annotations in Java is all about adding meta-data facility to the Java Elements. Like Classes, Interfaces or Enums, Annotations define a type in Java and they can be applied to several Java Elements. Tools which will read and interpret the Annotations will implement a lot of functionalities from the meta-information obtained.

Annotation is created based on the interface.

Adding ‘@’ before the keyword interface to declare an annotation type.

All annotations consist only method declarations.

These methods act much like fields.


@interface MyAnnotation {

String stringValue();

}

Program 1


@interface MyAnnotation {

String stringValue();

int intValue();

}

public class MainClass {

// Annotate a method.

@MyAnnotation(stringValue = "Annotation Example", intValue = 100)

public static void myMethod() {

}

}

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.

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

1.1   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() {

------------

}

1.2  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(){

--------

}

1.3  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

Java provides three standard annotations and four standard meta-annotations.

 

  1. There are three annotation types in Java 5: Deprecated, Override, and Suppress Warnings.(Simple or Inbuilt  Annotations)
  2. There are four other annotation types that are part of the java.lang.annotation package: Documented, Inherited, Retention, and Target. (Meta Annotations)

Four are imported from java.lang.annotation: @Retention, @Documented, @Target, and

@Inherited.

Three, @Override, @Deprecated, and @SuppressWarnings, are included in java.lang.

 

3.     SIMPLE ANNOTATIONS

3.1 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.

Program 2 :

3.2 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'");

}

}

<span style="color: #008000;"><strong>Now lets try to invoke this method from inside the other class:</strong></span>

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();

}

On compiling the class Depricated_method does not generate any error. It displays a note.

3.3 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

Consider the above example with an additional line


public class Test_Deprication {

public static void main(String arg[]) throws Exception {

new Test_Deprication();

}

@SuppressWarnings( {"deprecation"} )

public Test_Deprication() {

Deprecated_method d = new Deprecated_method();

d.showSomething();

}

While compilation the warning will not be displayed as it will be suppressed using the Suppresswarning annotation

4.     META ANNOTATIONS 

4.1 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.

Example:


( import  java.lang.annotation.*;  ) //Targg

@Target(ElementType.METHOD)

public @interface At {

public String show();

}

Now lets create a class that use the Test_Element annotation:

public class Test_Annotations {

public static void main(String arg[]) {

new Test_Annotations().show();

}

@At(show="Hi ! How r you")

public void show() {

System.out.printf("Testing Target Element annotation");

}

}

If we use the  @At before other elements  error occurs  as type mismatch at Target. This annotation is used to specify the application of annotation for a unique element.

4.2 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.

Program:


//Reten

// Print default values of annotation members using Retention Policy

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)

@interface MyAnno {

String str() default "Testing";

int val() default 9000;

}

class Meta3 {

@MyAnno()

public static void myMeth() {

Meta3 ob = new Meta3();

try {

Class c = ob.getClass();

Method m = c.getMethod("myMeth");

MyAnno anno = m.getAnnotation(MyAnno.class);

System.out.println(anno.str() + " " + anno.val());

} catch (NoSuchMethodException exc) {

System.out.println("Method Not Found.");

}

}

public static void main(String args[]) {

myMeth();

}

}

 OUTPUT:  Testing 9000 

Program:


//Print1

// Print all the values of  Annotation

import java.lang.annotation.Annotation;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.reflect.Method;

// A simple annotation type.

@Retention(RetentionPolicy.RUNTIME)

@interface MyAnnotation {

String stringValue() default "defaultString";

int intValue() default 101;

}

@MyAnnotation(stringValue = "for class", intValue = 100)

public class MainClass {

// Annotate a method.

@MyAnnotation(intValue = 100)

public static void myMethod() {

}

public static void main(String[] arg) {

try {

MainClass ob = new MainClass();

Method m = ob.getClass( ).getMethod("myMethod");

Annotation[] annos = m.getAnnotations();

System.out.println("All annotations for myMeth:");

for(Annotation a : annos)

System.out.println(a);

} catch (Exception exc) {

}

}

}

OUTPUT:

All annotations for myMeth:

@MyAnnotation(intValue=100, stringValue=defaultString)

4.3 Documented Annotation

The documented annotation indicates that an annotation with this type should be documented by the javadoc tool. By default, annotations are not included in javadoc. But if @Documented is used, it then will be processed by javadoc-like tools and the annotation type information will also be included in the generated document.

Program  //Ex4


 

//To view the use of Documented annotation

import java.lang.annotation.*;

@Documented

@interface Test_Documented {

String doTestDocument();

}

@interface Test_Retention{

String doTestRetention();

}

public class Ex4 {

public static void main(String arg[]) {

new Ex4().doSomeTestRetention();

new Ex4().doSomeTestDocumented();

}

@Test_Retention (doTestRetention="Hello retention test")

public void doSomeTestRetention() {

System.out.printf("Testing annotation 'Retention'");

}

@Test_Documented(doTestDocument="Hello document")

public void doSomeTestDocumented() {

System.out.printf("Testing annotation 'Documented'");

}

}

Output:(Command Prompt)

Testing annotation ‘Retention’Testing annotation ‘Documented’

Output of a Document tool

4.4 Inherited Annotation:

This is a bit of a complex annotation type.

If you define an annotation with the @Inherited tag, then annotate a class with your annotation, and finally extend the class in a subclass, all properties of the parent class will be inherited into its subclass.

Program

First, define your annotation:


@Inherited

public @interface myParentObject {

boolean isInherited() default true;

String doSomething() default "Do what?";

}

Next, annotate a class with your annotation:

@myParentObject

public Class myChildObject {

}

As you can see, you do not have to define the interface methods inside the implementing class. These are automatically inherited because of using the @Inherited tag.

What would happen if you define the implementing class in old-fashioned Java-style? Take a look at this—defining the implementation class in an old-style-java way:


public class myChildObject implements myParentObject {

public boolean isInherited() {

return false;

}

public String doSomething() {

return "";

}

public boolean equals(Object obj) {

return false;

}

public int hashCode() {

return 0;

}

public String toString() {

return "";

}

public Class annotationType() {

return null;

}

}

Do you see the difference? You can see that you will have to implement all the methods that the parent interface owns. Besides the isInherited() and doSomething() methods from myParentObject, you will have to implement the equals(), toString(), and hasCode() methods of java.lang.Object and also the annotationType() method of java.lang.annotation.Annotation class. It does not matter whether you want to implement these methods or not; you will have to include these in your inherited object.

Filed in: Z-A All Java Codes

No comments yet.

Leave a Reply