Java annotations

 Do you want to add information about the code as meta data? If your answer is yes then this is the feature to add annotations.

Why is it needed?

It is used to provide supplementary information about the classes, member variables and functions.

What is the difference between annotations and comments?

Annotations provides the meta data about coding which can be used by tools and compilers. But comments are simple information to know about coding.

Syntax:

‘@’ annotation name                                                                                                                                       

Annotation types:

Annotations can be classified into the following types..

1. Built- in annotations:

These are annotations created by the java itself

Eg: ‘@Depreccated’, ’@Override’, ‘@SuppressWarnings’

2. Custom annotations:

The user can create this type of annotations.

Eg:

‘@interface’

Java code for built-in annotation:

These are included in java package itself. Here ‘@Override’ is used.

This annotation is used to tell the compiler that this base class code is overridden.

Base class or Super class: sClass1

Child class: cClass

Method: display() – same method with two definition is called overridden.  

Sample Code:

   class sClass1 {

       void display() {

           System.out.println("This is the Super Class");

       }

   }

   class cClass extends sClass1 {

       @Override

       void display() {

           System.out.println("This is the Child Class");

       }

   }

Next type of annotation is given below.

Java code for custom annotation:

              User defined annotations are called custom annotation. Here, the custom annotations are listed below..

@Retention :it specifies how long the annotations are retained.

@Target : It specifies the kind of program, the annotations are applicable.

@interface : user defined interface

@custAnnotation: user defined custom annotation name.

Sample Code:

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface custAnnotation {

    String name();

}

public class egClass {

    @custAnnotation("This is the custom annotation")

    public void egMethod() {

        // Method implementation

    }

}

These are the sample codes used to provide annotations in both built-in and custom type. Hope this codes are useful to you.Keep coding!!!

No comments:

Post a Comment