Annotation
Definition
In a java program, we can define metadata in multiple ways;
metadata refers to data about data. It means metadata tells something about
data in readable or understandable format.
Metadata exists in a program but it will not be a part of
program execution.
Today while working with program (java application) metadata
can be provided in following ways:
1.
With comments
2.
With Access modifiers
3.
With xml files
4.
With Annotations
A comment tells
something about the line of code about a program so it is a metadata.
If we add final
modifier to a class then it tells a compiler that class can’t be extended.
So it helps the compiler to detect errors. Here final modifier is a metadata.
In xml files for
each data or value a tag is associated that tag tells about that value. So it
is a metadata.
In application development the java developers are creating
heavily xml files and it is increasing the burden of developers so to reduce
the burden and also to make reduction in the size of xml file in a project in java
5 sun micro system introduced annotations.
Annotations are
also a form of metadata which can be specified in java source code instead of
in xml files.
Every annotation is processed by some program. These
programs can be a compiler, jvm or parser program. The compiler and jvm can
process only the annotations which are part of java Ee(JSE).
In java SE only
three annotations are given:
1. @Override
2. @Deprecated
3. @SuppressWarings
@Override is
processed by java compiler and remaining two is processed by jvm. The above
annotations are part of java.lang
package.
The symbol @
indicates a java compiler that it is an annotation. So a compiler does not
raise any errors for those lines at compile time.
Creating annotations
Through annotations if we want to add metadata in java code
first of all that annotation must be created with one or more elements.
Annotation can be created with special key word @interface and stating letter of
annotation must be capital.
While creating annotation only it is given that for which type
of elements in java code the annotation is useful to write the metadata.
For example:
@Target(ElementType.METHOD)
Public @interface India
{
//elemets
}
In a java program @India annotation India is applicable for
method only.
Types of ElementType
1. ElementType.TYPEà
indicates class or interface
2. ElementType.METHODàindicates
method
3. ElementType.FIELDàfor
instance variable
4. ElementType.CONSTRUCTORàconstructor
5. ElementType.PARAMETERàmethod
parameter
While creating an annotation a visibility mode is attached.
We call this visibility mode as RetentionPolicy
There are three
visibility modes:
1. Source level
2. Class level
3. Jvm level
If visibility mode is source
level then it is invisible to compiler and jvm.
Class level
visibility is for compiler not for jvm.
Example:
@Override annotation is visible to compiler but not to jvm.
Jvm level
visibility makes an annotation as visible to both jvm.
The constant of RetentionPolicy
are:
1. RetentionPolicy.SOURCEàsource
level
2. RetentionPolicy.CLASSàclass
level
3. RetentionPolicy.RUNTIMEàjvm
level
Example:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
Public @interface India
{
//elemets
}
Here, the annotation @India
is visible to both compiler and jvm.
Every annotation is a special interface, it contains
elements but not variable or method.
Elements in annotations can have default values.
The elements without default value must be passed at the
time when that annotation is used in a java program.
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
Public @interface India
{
String msg() default “”;
Int version() default 1;
String course();
Int duration() optional;
}
The above annotation contains four elements, where course ()
is mandatory with annotation.
@India(msg=”welcome” , course=”java”)àvalid
@India( course=”java”)àvalid
@India(version=10 , msg=”welcome” , course=”java”)àvalid
@India(duration=2 , course=”java”)àvalid
@India(version=10 , msg=”welcome”)à invalid
@India(version=10 , msg=”welcome” , duration=120)àinvalid
Note:
If annotation contains only one element with the name value
then at time of adding the annotation in the java program we can pass directly
the value or with the element name as value.
Example:
@SuppressWarnings(“deprecation”);àvalid
@SuppressWarnings(value=”deprecation”);àvalid
Lets have the example
//Annotated.java
class Annotated {
@Test(info = "AWESOME")
public void foo(String myParam) {
System.out.println("This is " + myParam);
}
}
//Demo.java
public class Demo
{
public static void main(String[] args) throws Exception
{
TestAnnotationParser parser = new TestAnnotationParser();
parser.parse(Annotated.class);
}
}
//Test.java
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
String info() default "";
}
//TestAnnotationParser.java
import java.lang.reflect.*;
class TestAnnotationParser
{
public void parse(Class clazz) throws Exception
{
Method[ ] methods = clazz.getMethods();
for (Method method : methods)
{
if (method.isAnnotationPresent(Test.class))
{
Test test = method.getAnnotation(Test.class);
String info = test.info();
if ("AWESOME".equals(info))
{
System.out.println("info is awesome!");
}
}
}
}
}
Lets have the example
//Annotated.java
class Annotated {
@Test(info = "AWESOME")
public void foo(String myParam) {
System.out.println("This is " + myParam);
}
}
//Demo.java
public class Demo
{
public static void main(String[] args) throws Exception
{
TestAnnotationParser parser = new TestAnnotationParser();
parser.parse(Annotated.class);
}
}
//Test.java
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
String info() default "";
}
//TestAnnotationParser.java
import java.lang.reflect.*;
class TestAnnotationParser
{
public void parse(Class clazz) throws Exception
{
Method[ ] methods = clazz.getMethods();
for (Method method : methods)
{
if (method.isAnnotationPresent(Test.class))
{
Test test = method.getAnnotation(Test.class);
String info = test.info();
if ("AWESOME".equals(info))
{
System.out.println("info is awesome!");
}
}
}
}
}