Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

Annotations By Mr.

SomasekharReddy

Annotations
Introduction
 Annotations are java language feature introduced in java5

 Annotations can be used for


o Automatic generation of configuration files(deployment descriptor, bean
classes,etc)
o Automatic generation of code for testing, logging, database integration etc.

 Annotations let you avoid writing boiler plate code under many circumstances by
enabling tools to generate it from annotations in the source code.

 Java5 platform introduces a simplified declarative programming model with


annotations. With java 5 technology, Xml deployment descriptors are now optional.
Instead of describing the components with the xml file we can describe with the
annotations in the java source file itself.

 It also eliminates the need of maintaining side files that must be kept upto the date
with changes in source file.

 Annotations supply additional instructions to the compiler to behave according to the


annotations applied for a class.

 Annotations do not directly effect program semantics, but they do effect the way
programs are treated by tools and libraries.

Annotations Topics

MetaData

a) Introduction to MetaData
b) Types of MetaData
c) Value of MataData

Annotations

a) Why Annotations and Why it matters?


b) World before Annotations
c) What is an Annotation

Annotations as far as Java6

a)Meta(java.lang.annotation package)

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 1
Annotations By Mr. SomasekharReddy

1) @Documented

2) @Inherited

3) @Target

4) @Retention

b)Standard(java.lang package)

1) @Override

2) @Depricated

3) @SuppressWarnings

Types of Annotations

a) Marker
b) SingleMarker
c) MultiMarker or Full Annotation
d) Complex or Nested Annotation

User defined Annotations

Annotation Processing and Life cycle of Annotations

Custom Annotation processor

Reflections

Advantages and Limitations of Annotations

Metadata

Data about the data is called metadata

Examples : documentation comments, ResultSetMetaData, user_tables etc

Types of Metadata

There are 2 types of metadata

 Internal metadata
 External metadata

 The data which is used to describe the component inside the source file itself is
called internal metadata.

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 2
Annotations By Mr. SomasekharReddy

Ex : /**-----------*/

 The data which is used to describe components externally to the source file is called
external metadata.

Ex: xml file like web.xml

NOTE: With annotations we can give the metadata within the same source file
itself.

 If there are any problems in xml file we will come to know about them at runtime.
But with annotations we can solve them at compile time itself or we can make it
checked at runtime.

Value of Metadata

We can get the value of metadata using some tools like

1) to get the documentation comments of .java file --“javadoc”

2) to create xml files and java src files to EJB -- “XDoclet”

3) to get servlets metadata from web.xml -- “parsers”

Why Annotations ?

 External tools like javadoc(.html), XDoclet(.Java,.xml) are used to create


particular files only.
 Marker interfaces(Serializable, Cloneable, RandomAccess, Remote,
SingleThreadModel…etc.) can be applied to only classes but we can’t apply to
other java elements
 transient keyword can be applied to only variables

NOTE: Annotations can be applied to any type of java elements

Why annotations matters?

 Annotations are meant for adding metadata to all java elements like packages,
classes, methods, fields etc.
 Annotations can be used as marker interface
 Annotations can be processed at 3 levels
1) Source
2) Class
3) Runtime

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 3
Annotations By Mr. SomasekharReddy

World before Annotations

Before annotations Xml was used to annotate java code and some tools used to
get annotated data.

What are annotations?

 In short annotations are called metadata of any java elements. Annotations are
said to be annotate a java element.
 An annotation associates orbitrary information or metadata with a java element.

Annotations as far as java6:

Meta Annotations

 Meta Annotations can be imported from java.lang.annotation package


 Meta Annotations are used to define other Annotations means custom annotations.
 @Retention, @Target, @Documented, @Inherited are called Meta annotations

@Documented

If we use this annotation to a java element that annotation will be available in


the java documentation when we apply our class to “javadoc” tool.

@Inherited

If we apply this annotation to any custom annotation that will be available in the
child classes also

@Target

This annotation is used to tell to which java element you want to apply
annotations.

If we don’t specify @Target annotation it will be applicable for all java elements.

@Retention

This annotation is used to specify up to which level the annotation behavior will be
available(source/class/runtime).

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 4
Annotations By Mr. SomasekharReddy

Example on @Documented

DocumentedAnn.java
1. package com.nit.annotation;
2. import java.lang.annotation.Documented;
3. @Documented
4. public @interface DocumentedAnn {
5.
6. }

DocumentedDemo.java
1. package com.nit.annotation;
2.
3. /**
4. * @author sekhar
5. * This is a sample class demontrating meta annotations
6. *
7. */
8. @DocumentedAnn
9. public class DocumentedDemo {
10.
11. /**
12. * this method doesn't contain any great logic
13. */
14. public static void main(String[] args) {
15.
16. }
17. }

C:\> javadoc DocumentedDemo.java => *.html will be generated

NOTE : Now open index.html file, you can find “@DocumentedAnn” annotation. Now remove
“@Documented” annotation on “@DcumentedAnn” and generate javadocs once again, in the
generated javadocs we don’t find “@DcumentedAnn” annotation.
Source Code of @Documented
1. @Documented
2. @Retention(RetentionPolicy.RUNTIME)
3. @Target(ElementType.ANNOTATION_TYPE)
4. public @interface Documented {
5. }

Example on @Inherited

MyAnnotation.java
1. package com.nit.annotation;
2. import java.lang.annotation.Documented;
3. import java.lang.annotation.Inherited;
4. import java.lang.annotation.Retention;
5. import java.lang.annotation.RetentionPolicy;
6.
7. @Documented

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 5
Annotations By Mr. SomasekharReddy

8. @Inherited
9. @Retention(RetentionPolicy.RUNTIME)
10. public @interface MyAnnotation {
11.
12. }

Parent.java
1. package com.nit.annotation;
1. @MyAnnotation
2. public class Parent {
3.
4. }

Child.java
1. package com.nit.annotation;
2. public class Child extends Parent{
3.
4. }

InheritedDemo
1. package com.nit.annotation;
2. import java.lang.annotation.Annotation;
3. public class InheritedDemo {
4. public static void main(String[] args) {
5. Class parentClass=Parent.class;
6. Class childClass=Child.class;
7. Annotation[] annotations=parentClass.getAnnotations();
8. System.out.println("Annoations of parent class:"+annotations.length);
9. Annotation[] annotations1=childClass.getAnnotations();
10. System.out.println("Annotations inherited to child class from Parent
11. class are:"+annotations1.length);
12. Annotation[] annotations2=childClass.getDeclaredAnnotations();
13. System.out.println("Annotations of child class
14. are"+annotations2.length);
15. }
16. }

NOTE: remove “@Inherited” annotation on “@MyAnnotaion”, then see the


difference in the output.
Source Code of @Documented
1. @Documented
2. @Retention(RetentionPolicy.RUNTIME)
3. @Target(ElementType.ANNOTATION_TYPE)
4. public @interface Inherited {
5. }

Java.lang.annotation.Annotation

 In java every annotation implicitly implements Annotation interface. If we


implement Annotation interface explicitly to any class that won’t behave like an
Annotation.

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 6
Annotations By Mr. SomasekharReddy

public class MyAnnotation implements Annotation {


…………………
}

 In the above example MyAnnotation is not an Annotation.

@Target

 While defining Annotation we should specify the Target type i.e should the annotation
can be used to Annotation class or method or some other java elements.

 Target Annotation is a meta Annotation. It is defined to annotate other annotations.

 Target takes one argument which must be a constant from ElementType


enumeration. this argument specifies the types of declarations to which annotation
can be applied.

 An annotation targeted to ElementType.TYPE cannot be applied to method, field,


local-variables, constructors and parameters. Violation of this will result to
compilation error. The constants are shown in the below table.

Type Annotation can be applied to

ElementType.TYPE Class,interface,enumeration

ElementType.METHOD Methods

ElementType.FIELD Fields

ElementType.PARAMETER Parameters

ElementType.CONSTRUCTOR Constructors

ElementType.LOCAL_VARIABLE Local variables

ElementType.ANNOTATION_TYP Another annotation


E

ElementType.PACKAGE Package

Source code of @Target


1. @Documented
2. @Retention(RetentionPolicy.RUNTIME)
3. @Target(ElementType.ANNOTATION_TYPE)
4. Public @interface Target{

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 7
Annotations By Mr. SomasekharReddy

5. ElementType[] value;
6. }
Source code of ElementType
1. Public enum ElementType{
2. TYPE, FIELD, CONSTRUCTOR, METHOD, PARAMETER, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE
3. }

Examples on @Target

Q.) Define an annotation which will be applicable to interfaces, classes, enumerations and that should be
available in the documentation and that should not be inherited to child classes.

1. @Documented
2. @Target(ElementType.TYPE)
3. Public @ interface MyAnnotation{
4. }

Q.) Define an annotation which will be applicable to classes, methods, local variables.

1. @Target({ElementType.TYPE, ElementType.METHOD, ElementType.LOCAL_VARIABLE})


2. Public @interface MyAnnotation{
3. }

Note : If we don’t specify any @Target annotation, then that will be applicable for all
elements.

@Retention

 Retention determines at what point an annotation discarded. Java defines 3 such


policies. Those are encapsulated with in java.lang.RetentionPolicy enumeration.
they are

 RUNTIME
 CLASS
 SOURCE

 An annotation with RetentionPolicy.SOURCE is retained in the source file and is


discarded during compilation.

 RetentionPolicy.CLASS for storing in ‘.class’ file during the compilation. It is not


available to the JVM at runtime.

 An annotation with RetentionPolicy.RUNTIME is stored in ‘.class’ file during the


compilation and is available to jvm during runtime. Thus RUNTIME RetentionPolicy
offers greatest annotation persistent.

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 8
Annotations By Mr. SomasekharReddy

Source code of @Retention


1. @Documented
2. @Retention(RetentionPolicy.RUNTIME)
3. @Target(ElementType.ANNOTATION_TYPE)
4. Public @interface Retention{
5. RetentionPolicy value ();
6. }

Source code of RetentionPolicy


1. public enum RetentionPolicy {
2. SOURCE, CLASS, RUNTIME
3. }

Example of @Retention

Q.) Define an annotation that is available at runtime and is applicable to fields only.

1. @Retention(value=RetentionPolicy.RUNTIME)
2. @Target(value=ElementType.FIELD)
3. Public @interface MyAnnotation{
4. }

Q.) Define an annotation which is available at Source level and at runtime?

1. @Retention({RetentionPolicy.SOURCE,RetentionPolicy.RUNTIME})
2. // (OR)
3. @Retention(value=RetentionPolicy.SOURCE)
4. @Retention(value=RetentionPolicy.RUNTIME)
5. Public @interface MyAnnotation{
6. }

The above way of applying the RetentionPolicy is illegal. Multiple RetentionPolicies


cannot be applied.

1. @Retention(RetentionPolicy.RUNTIME)
2. Public @interface MyAnnotation{
3. }

 All the meta annotations Target type is ANNOTATION_TYPE


 For all meta annotations the RetentionPolicy is RUNTIME
 All meta annotations are documentable
 All meta Annotations are not inheritable
 If you don’t specify the Target type will be applicable for all the elements
 Default Retention value is CLASS

Q.) Write an annotation which will be retained in the class file only but not available to JVM.

1. @Retention ( RetentionPolicy.CLASS)

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 9
Annotations By Mr. SomasekharReddy

2. Public @interface MyAnnotation{


3. ………..
4. }

Standard Annotations

 Standard annotations are available in java.lang package.

 Standard annotations are used to annotate our java code directly.

 Standard annotations available are


1. @Override
2. @Deprecated
3. @SuppressWarnings

 @Override is retained only in the source code.

 @Deprecated is available in ‘.class’ file and available to JVM also

 @SuppressWarnings is available in the source file only.

@Override

 It indicates that a method is intended to override a method of a super class in the


sub class.

 The two most commonly made mistakes which are never detected by the java
compiler are

1. the overridden method in sub class is misspelled.


2. the methods signature of sub class does not match the super class method
signature

 this will result in the sub class method can not be treated as overriding method

 To overcome this problem java 1.5 introduced @Overridde annotation.

 It is a marker annotation that can be used only on methods

 A method annotated with @Override must override a method from a super class if not
we will get compile time error.

Example on @Override

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 10
Annotations By Mr. SomasekharReddy

Square.java
1. package com.nit.annotation;
2. public class Square{
3. public void square(int a, int b) {
4. System.out.println("square class method called");
5. System.out.println(a*a+2*a*b+b*b);
6. }
7. }

BetterSquare.java
1. package com.nit.annotation;
2. public class BetterSquare extends Square{
3. @Override
4. public void sqare(int a,int b) {
5. System.out.println("Better Square class method called");
6. System.out.println((a+b)*(a+b));
7. }
8. }

OverrideDemo.java
1. package com.nit.annotation;
2. public class OverrideDemo {
3. public static void main(String[] args) {
4. Square s= new BetterSquare();
5. s.square(10, 20);
6. }
7. }

NOTE: In the above exmaple in BetterSquere class if we don’t write @Override


annotation, our intended method(overriding method) will not be called. If we apply
@Override annotation, if it is not overriding it will give compilation error.

Source code of @Override


1. @Target(ElementType.METHOD)
2. @Retention(RetentionPolicy.SOURCE)
3. public @interface Override{
4.
5. }

@Deprecated

 Java provides a mechanism to express deprecation. As new classes invented its API
changes naturally, method names are renamed for consistency, new and better
methods are added and fields may change.

 Some changes introduce problems, we need to keep the old API available until
developers habituated to new one. But we don’t want to continue them in the future.

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 11
Annotations By Mr. SomasekharReddy

 The word deprecated is used in java to inform the programmer that an element of
code is dangerous to use or an alternative element is available for the same.

 The compiler generates a warning when we use deprecated elements.

Example on @Deprecated
1. public class DeprecatedDemo{
2. /**
3. * @deprecated this method got deprecated it better
4. * to use {@link BetterSum#sum(int, int)}
5. */
6. @Deprecated
7. public void sum ( int a, int b) {
8. System.out.println(a+b);
9. }
10.
11. public static void main(String[] args)
12. {
13. DeprecatedDemo demo= new DeprecatedDemo();
14. demo.sum();
15. }
16. }

NOTE: when we call sum() method, it will show warning, so that the method got deprecated

Source code of @Deprecated


1. @Documented
2. @RetentionPolicy.RUNTIME)
3. public @interface Deprecated{
4.
5. }

@SuppressWarnings

 SuppressWarnings annotation indicates to the compiler to suppress all the compiler


warnings in the annotated code element including its sub elements or block.

 We should use @SuppressWarnings when we know that we are using on API which
results warnings, have taken possible precautions and therefore we don’t want the
compiler to warn about the same.

Example on @SuppressWarnings
1. package com.nit.annotation;
2. import java.util.ArrayList;
3. import java.util.List;
4. //@SuppressWarnings("deprecation ")
5. public class SuppressWarningDemo {
6. @SuppressWarnings("all")

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 12
Annotations By Mr. SomasekharReddy

7. public static void main(String[] args) {


8. List list=new ArrayList();
9. list.add("hi");
10. list.add("hello");
11. System.out.println(list);
12. }
13. public void test(){
14. Int a;
15. }
16.
17. }

Source code of @SuppressWarnings


1. @Target({TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE})
2. @Retention(RetentionPolicy.SOURCE)
3. public @interface SuppressWarnings{
4. String[] value();
5. }

The following are different values for SuppressWarning annotation

all, boxing, cast, dep-ann, deprecation, fallthrough, finally, hiding, incomplete-switch, nls, null, rawtypes,
restriction, serial, static-access, synthetic-access, unchecked, unqualified-fieldaccess
Annotation TYPE FIELD METHOD PARAMETER CONSTRUCTOR LOCAL-VARIABLE PACKAGES ANNOTATION-
type TYPE

@SuppressW Applicable Applicable Applicable Applicable Applicable Notapplicable Notapplicable


Applicable
arnings

@Override Notapplicable Notapplicable applicable Notapplicable Notapplicable Notapplicable Notapplicable Notapplicable

@Deprecated Applicable Applicable Applicable Applicable Applicable Applicable Applicable applicable

Enum types

 An enum type is a type whose fields consist of a fixed set of constants.


 Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST),
days of the week, planet names…etc.
Simple enum. The ; after the last element is optional, when this is the end of enum definition.
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE; //; is optional
}

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 13
Annotations By Mr. SomasekharReddy

Enum embedded inside a class. Outside the enclosing class, elements are referenced as Outter.Color.RED,
Outter.Color.BLUE, etc.

public class Outter {


public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE
}
}
Enum that overrides toString method. A semicolon after the last element is required to be able to compile it. More
details on overriding enum toString method can be found here.

public enum Color {


WHITE, BLACK, RED, YELLOW, BLUE; //; is required here.

@Override public String toString() {


//only capitalize the first letter
String s = super.toString();
return s.substring(0, 1) + s.substring(1).toLowerCase();
}
}
Enum with additional fields and custom constructor. Enum constructors must be either private or package default,
and protected or public access modifier is not allowed. When custom constructor is declared, all elements declaration
must match that constructor.

public enum Color {


WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

private int code;

private Color(int c) {
code = c;
}

public int getCode() {


return code;
}
Enum that implements interfaces. Enum can implement any interfaces. All enum types implicitly
implements java.io.Serializable, andjava.lang.Comparable.

public enum Color implements Runnable {


WHITE, BLACK, RED, YELLOW, BLUE;

public void run() {


System.out.println("name()=" + name() +
", toString()=" + toString());
}
}
A sample test program to invoke this run() method:

for(Color c : Color.values()) {
c.run();
}

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 14
Annotations By Mr. SomasekharReddy

Or,

for(Runnable r : Color.values()) {
r.run();
}

Example on Enum Types

Direction.java
1. package com.neo.enums;
2.
3. public enum Direction {
4. NORTH(1), EAST(2), SOUTH(3), WEST(4);
5.
6. private int code;
7.
8. private Direction(int code) {
9. this.code = code;
10. }
11.
12. public int getCode(){
13. return code;
14. }
15.
16. }

EnumDemo.java
1. package com.neo.enums;
2.
3. public class EnumDemo {
4. public static void main(String[] args) {
5. sop("Accessing perticular instance...");
6. Direction direction = Direction.SOUTH;
7. System.out.println(direction);
8. sop("...all instances of Direction are...");
9. for (Direction direction2 : Direction.values()) {
10. sop(direction2 + "==>" + direction2.getCode());
11. }
12.
13. }
14.
15. public static void sop(Object object) {
16. System.out.println(object);
17. }
18. }

Types of Annotations
VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 15
Annotations By Mr. SomasekharReddy

There are 4 types of annotations

1. marker annotation
2. single member annotation
3. multimember (or)full annotation
4. complex (or) nested annotation

Marker Annotation

 This annotation is just like marker interface. So marker annotations can be used as
an alternative to marker interfaces.

 Marker Annotation is a special kind of annotation that contains no members. Its main
purpose is to mark java elements. The presence of marker annotation carries a
special meaning to a java element.

Ex : Override, Deprecated, Documented, Inherited

Creation of marker annotation


Immutable.java
19. @Target(ElementType.TYPE)
20. public @interface Immutable{
21.
22. }

Usage of marker annotation


Account.java
1. @Immutable
2. public class Account{
3.
4. }

Single member annotation

 A single member annotation contains only one member

 It works like a normal annotation except that it allows a short hand form of specifying
the value of the member. when only one member is present (with name “value”) you
can simply specify the value for that member when the annotation is applied. We
don’t need to specify the name of the member.

 However in order to use this short hand the name of the member must be value.

Ex: SupressWarnings, Retention, Target …etc.

Example Usage

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 16
Annotations By Mr. SomasekharReddy

Public @interface Author{ @Author(“sekhar”)


String value(); public class Demo{
} }
@Author(value=“sekhar”)
public class Demo{
}

Example Usage

Public @interface Author{ @Author(name=“sekhar”)


String name(); public class Demo{
} }

 Annotations can have array members also.


 Array members can be primitive type, String, enum type or other annotation type or
class only.

Example Usage

Public @interface Author{ @Author({“kesav”,”sekhar”,”somu”})


String[] value(); public class Demo{
} }
@Author(value={“kesav”,”sekhar”,”somu”})
public class Demo{
}

 When the annotation has a member while using this annotation we should specify the
member value otherwise compilation error will be generated.

 Annotation members can have default values. Those default values will be used if we
don’t specify the value for a member when the annotation is applied. Default value is
specified by adding default clause to a member’s declaration.

Example Usage

Public @interface Author{ @Author(”somu”) // overridden the default


String value() default “sekhar”; public class Demo{
} }
@Author // default value will be taken
public class Demo{

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 17
Annotations By Mr. SomasekharReddy

Multimember Annotation

 An annotation which will contain more than one member is called multimember
annotation or full annotation. While applying multimember annotation shorthand form
is not allowed.

 While applying the multi member annotation, members should be specified as key-
value pairs separated by ‘,’(comma).

Example Usage

public @interface Author{ @Author(name=”sekhar”, version=”1.8”)


String name(); public class Demo{
String version() default “1.6”; }
}

Subject.java Demo.java
public enum Subject { @Author(subName=Subject.SPRING,maritalStatus=false,
STRUTS, SPRING, HIBERNATE; version=1.0)
} public class Demo {

Author.java }
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
public @interface Author {
String[] name() default "sekhar";
double version() default 1.0;
boolean maritalStatus() ;
Subject subName();
}

Complex (or) Nested Annotation

 Defining an annotation inside another annotation is called nested annotation.

Licence.java
1. public @interface Licence{
2. String place() default “Tenali”;
3. }

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 18
Annotations By Mr. SomasekharReddy

TrafficOfficer.java
1. public @interface TrafficOfficer {
2. Licence licence();
3. String showMeLicence();
4. }

Demo.java
1. @TrafficOfficer(licence=@Licence(place="Hyd"),showMeLicence="sorry sir take 200Rs")
2. public class Demo {
3. }

APT(Annotation Processor Tool)

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 19
Annotations By Mr. SomasekharReddy

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 20
Annotations By Mr. SomasekharReddy

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 21
Annotations By Mr. SomasekharReddy

 Annotation processors are run by javac before the input source files
are compiled.
 Annotation processors must implement the javax.annotation.processing.Processor
interface to get registered with javac. This interface has methods that inform javac about
what the annotation processor does, including what annotations it processes and what
source version it supports.
 Extending the javax.annotation.processing.AbstractProcessor class is a convenient way to
write a processor since annotations can be used to provide the value the methods return.
When extending AbstractProcessor, the only method that needs to be implemented is
process.
 A processor can get run multiple times in one javac invocation. If the test (!
roundEnv.processingOver()) is removed, "Note: Hello World" will be printed twice. The
javac infrastructure can call a processor's process method once per round. A round
corresponds to analyzing a set of types.
 Processors get access to resources, like a Messager, by getting helper objects from different
environments. The ProcessingEnvironment (the processingEnv field in AbstractProcessor)
provides round-independent utilities while the RoundEnvironment argument to process
provides round-dependent ones.

Custom Annotation Processor


Processing annotations at compile time

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 22
Annotations By Mr. SomasekharReddy

 Annotation processor is a module that plugs in to compiler API and gets called during
compilation.

 We can report errors, warnings and we can generate new types and new resources
using custom annotation processor. But we cannot change the existing code. Custom
annotation processor can’t see the source code directly but they can see type
System.

 Like reflection API except introspecting once source code at compile time we can’t do
anything on live objects at runtime.

 Annotation processors are run by java compilers before the code is compiled.

Steps to develop custom annotation processor


Step1: Annotation processor must implement javax.annotation.processing.Processor
interface to get registered with java compiler. This interface has two methods0

1. init()
2. process()

Step2: Even our custom annotation processor can extend


javax.annotation.processing.AbsatractProcessor class. This is the adoptor class which
will provide default implementation for init() method.

Step3: Our custom annotation processor has to be annotated with following


annotations.

@SupportedAnnotationTypes(“*”)

@SupportedSourceVersion(SouceVersion.RELEASE_6)

Example on Annotation Processor

Demo.java
1. package com.nit.annotation;
2. @Note
3. public class Demo {
4. }

Note.java
1. package com.nit.annotation;
2. public @interface Note {
3. }

NoteAnnotationProcessor.java
1. import java.util.Set;

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 23
Annotations By Mr. SomasekharReddy

2. import javax.annotation.processing.AbstractProcessor;
3. import javax.annotation.processing.ProcessingEnvironment;
4. import javax.annotation.processing.RoundEnvironment;
5. import javax.annotation.processing.SupportedAnnotationType;
6. import javax.annotation.processing.SupportedSourceVersion;
7. import javax.lang.model.SouceVersion;
8. import javax.lang.model.element.TypeElement;
9. import javax.tools.Diagnostic.Kind;
10. @SupportedAnnotationTypes("*")
11. @SupportedSourceVersion(SourceVersion.RELEASE_6)
12. public class NoteAnnotationProcessor extends AbstractProcessor
13. {
14. ProcessingEnvironment env;
15. public void init(ProcessingEnvironment processingenv)
16. {
17. env=processingenv;
18. env.getMessager().printMessage(Kind.NOTE,"resouces are allocated");
19. }
20. public boolean process(Set annotations,RoundEnvironment roundEnv)
21. {
22. for(TypeElement object: annotations)
23. env.getMessager().printMessage(object.getSimpleName());
24. if(!roundEnv.processingOver())
25. env.getMessager().printMessage(Kind.ERROR,"please don't use note");
26. else
27. env.getMessager().printMessage(Kind.NOTE,"resources are released");
28. return true;
29. }
30. }

Compiling the above files

Compile Note.java,

C:\>NoteAnnotationProcessor.java

Compile Demo.java as

C:\>javac –processor NoteAnnotationProcessor Demo.java

Advantages of annotations
 Easy development
 Documentation
 Additional compiler checks
 Extending static checking
 Code analysis

Limitations
VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 24
Annotations By Mr. SomasekharReddy

 Annotations are having hardcoded configuration information. So changing


configuration is not possible declaratively.

 Annotations cannot extend another annotation.

 Annotation members should not have throws clause.

 Annotations cannot be generic

 Annotations members must be primitive types, Strings, enum types, annotation


types or arrays of preceding types only.

VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 25

You might also like