Skip to main content

Annotations in java


Annotations are java language feature introduced in java 5 version Annotations can be used for  Automatic generation of  configuration file(Deployment descriptor(web.xml),bean classes,etc)

Instead of describing the components   with the Xml file we can describe with the annotations in the  java source file itself.

MetaData:-
Data about the data is called as MetaData. The mainpurpose of Annotations in java apps to represent MetaData. to represent MetaData it is possible to  use comments directly. but commneted MetaData will be eliminated by  lexical-Analizer in compiler as part of compilation process,as  a result  commented meta data will be available in the respective .class files.
In general to simplyfy debugging,Testing & to execute Enterprise app like web-app,distributed app we have to bring the metadata upto runtime.
to achive this requirement we have to use Annotation over-comment.

In general to bring MetaData upto runtime it is possible to use XmlDocument like web.xml file, to provide the mapping details b/w url-patterns
& servlets to the servlet-container,struts-config.xml file  to provide all the Module respective configuration details etc..

To bring metadata upto runtime if we use above approach than all the java devlopers has to aware xml tech  separatly.

Conslusion:-
in java app to bring metadata upto run time  purely in the form of java alternative then we  have to use Annotations.
in java app all the Annotations will be processed by Annotation processing tool(APT) included internally in java Technology.
in java app Annotations will represent only metadata ,which will not give any effect to java application execution.
to declare any Annotation we have to use the  following syntax.

@interface Annotation-Name {

data -type var() default value;
-----------------------
-----------------------
-----------------------
}

Example:-
@interface Employee{

int eno();

String ename();

String eaddr() default"hyderabad";

}

if we want to apply annotations along with java programming constructs we have to provide the following syntax.

Syntax:-
@Anntation_Name(member1=value1,memeber2=value2....)

EXAMPLE:
@Employee(eno=121,ename="aaa",eaddr="ban")

class Manager

{
--
--
}

Every Annotation symbol is denoted by   @ symbol.

Standard Annotattions:-
Standard Annotations are avilable in  java.lang package
Standard Annotations are used to annotate our java code directly.
Standard Annotations

1)General-purpose Annotations:-
These are predeined annotations ,which will be used to describe some metadata,for the simple programming constructs.

1.@Override

2.@Deprecated

3.@SuppressWarnings

2) Meta-Annotations:-
Annoatations about the annotations is called as

MetaAnnotations. In general MetaAnnotations can be used to declare
another annotations

Example:
1)@Inherited  2)@Documented 

3) @Target  4) @Retention

@Override:-
The @Override annotation is used above methods  that override methods in a superclass.  If the method does not match a method in the  superclass, the compiler will give you an error.

The @Override annotation is not necessary in order to override a method in a superclass

Here is an example use of the @Override annotation:

public class MySuperClass {

  public void doTheThing() {

        System.out.println("Do the thing");
    }
}

public class MySubClass extends MySuperClass{

   @Override

    public void doTheThing() {

        System.out.println("Do it differently");
    }
}

In case the method doTheThing()  in MySuperClass changes signature so that
the same method in the supclass no longer  overrides it, the compiler will generate an error.
so A method annotated with @Override must   override a method from super class. other wise we will get Compiletime Error

SourceCode:-
@Target(ElementType.METHOD)

@Retention(RetentionPolicy.SOURCE)

public @interface Override

{

}

@Deprecated:-
java provides a mechanism to express deprecation . As new classes invented its API changes naturally, method names are renamed for consistenecy ,new and better methods are added    may change. some changes introduce problems ,
we need to keep the old API avilable until developers habituated
to  new one.But we don't want to continue them  in the future

The Word Deprecated generates a warring when we use deprecated elements.

@Documented

@Retention(RetionPolicy:RUNTIME)

public @interface Deprecated{
}

@SuppressWarinings:-
SuppressWarinings annotation indicates to the compilerto suppress(or) remove the warining messages.



Meta Annotation:-

1) @Inherited:-
In general in java app annotations are not inherited from super class to sub-class by default. if we want make any annotation to inherit from  super to sub class we have to @Inherited Annotation.

Example:
@Inherited

@interface Table{

}

@Table

class Emp{
}
class Manager extends Emp
{

}

2) Documented Annotation:-
In java app by default all annotations are not  documented when we prepare documentation for our java app.

if we want to make any annotation to incldue in the documentation we have to use @Documented Annotation.

3) @Target
The mainpurpose of this annotation is to define the target elements for the annotations at the time of declrations.

This annotation is multivalue annotation,it will take the following constants from element type as parameter.

TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE,PACKAGE. ALL

Example:
@Target(ElementType.METHOD,ElementType.TYPE,ElementType.FIELD)

4) Retention-Annotation:-
This annotation can be used to define  a particular scope to some other Annotation,here the scope of annotation may be source file(or) upto .class file

(or) upto run time.

Example:
@Retention(RetentionPolicy.RUNTIME)

Custom Annotations in Java
Creating custom annotation is similar to writing  an interface, except that it interface keyword  is prefixed with @ symbol.

Example :-
//course.java

import java.lang.annotation.*;

@Inherited

@Documented

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@interface Course{

String id() default "cj";

String name() default "corejava";

int fee() default 750;

}

//Student.java
public class  Student{

            String sid;

            String sname;

            Student(String sid,String sname){

                        this.sid=sid;

                        this.sname=sname;

            }

@Course(id="aj",name="Adv.java")

public void getStudentDetails()    {

System.out.println("Student-Details");

System.out.println("--------------");

System.out.println("Student Id :"+sid);

System.out.println("Student Name:"+sname);

}

}

Main.java

import java.lang.reflect.*;

class Main {

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

Student s=new Student("s1","aaa");

s.getStudentDetails();

Class c=s.getClass();

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

Course crs=(Course)m.getAnnotation(Course.class);

/*to get the Annotation() we should use getAnnotation(Class cls);

method from Method Object

*/

System.out.println(crs.getClass());

System.out.println("Course-Details");

System.out.println("-----------------");

System.out.println("Course-Id.."+crs.id());

System.out.println("Course-Name.."+crs.name());

System.out.println("Course-Fee.."+crs.fee());

}

}

Comments

Popular posts from this blog

Properties

Appendix A. Common application properties Various properties can be specified inside your  application.properties / application.yml  file or as command line switches. This section provides a list common Spring Boot properties and references to the underlying classes that consume them. Property contributions can come from additional jar files on your classpath so you should not consider this an exhaustive list. It is also perfectly legit to define your own properties. This sample file is meant as a guide only. Do  not  copy/paste the entire content into your application; rather pick only the properties that you need. # =================================================================== # COMMON SPRING BOOT PROPERTIES # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # =================================================================== # ---------...

Java Questions

1.WHAT IS JAVA? Java is a very simple, high level, Secured, Multithreaded, Platform independent, Object Oriented Programing Language. It was invented by "Gems Gosling" in SUN MICROSYSTEM for developing internet applications. ========================================================== 2.WHY JAVA IS VERY SIMPLE? its syntaxes are similar to c/c++. it omits many of the features that makes c and c++ complex, confusing and unsafe. java has inbuilt rich set of programs (API) sothat project development fast and easy. Note: In java we don't implement most horrible topics such as pointers, structures, union, operator overloading, multiple classes inheritance and many more. ========================================================== 3.IS JAVA SUPPORTS POINTERS? Java doesn't supports pointer but internally pointers are there in java software [JVM]. Java native language is C that means java language is developed using C language so Java software can have pointers in...

Stellar Data Recovery

Stellar Data Recovery Tips - पानी में डूबी हुई हार्ड डिस्क से कैसे डेटा रिकवर करें पानी में डूबी हुई हार्ड डिस्क से कैसे डेटा रिकवर करें पिछले कुछ हफ्तों बारिश के रूप में प्रकृति का कहर अपने चरम पर था , जिसकी वजह से चेन्नई शहर में जीवन प्रभावित हुआ । भूकंप से लेकर भारी बाढ़ तक , देश में इस साल प्राकृतिक आपदा के बारे में निरंतर खबरें चलती रही । प्राकृतिक आपदाओं ने मानव जीवन पर एक भयंकर रोक सी लगा दी । प्राकृतिक आपदा के बाद व्यवसायों को भी भारी नुकसान भुगतना पड़ा - प्राकृतिक आपदा से न केवल फिज़िकल नुकसान हुआ लेकिन मूल्यवान डेटा सिस्टम भी प्रभावित हुए ।   हम सब जानते हैं , डिजिटल उपकरण के लिए पानी कितना खतरनाक हैं । हम हमेशा अपने गॅडजेट्स जैसे मोबाइल फोन , कैमरा , लैपटॉप इत्यादि को पानी से दूर रखने के लिए विशेष सावधानी बरतते हैं । लेकिन हम प्राकृतिक आपदाओं के मामले में असहाय हो जाते हैं , जैसे हाल ही में चेन्नई में जो हुआ । ...