Professional Documents
Culture Documents
Annotations
Annotations
SomasekharReddy
Annotations
Introduction
Annotations are java language feature introduced in java5
Annotations let you avoid writing boiler plate code under many circumstances by
enabling tools to generate it from annotations in the source code.
It also eliminates the need of maintaining side files that must be kept upto the date
with changes in source file.
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)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
Reflections
Metadata
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.
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
Why Annotations ?
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
Before annotations Xml was used to annotate java code and some tools used to
get annotated data.
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.
Meta Annotations
@Documented
@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. }
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. }
Java.lang.annotation.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
@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.
ElementType.TYPE Class,interface,enumeration
ElementType.METHOD Methods
ElementType.FIELD Fields
ElementType.PARAMETER Parameters
ElementType.CONSTRUCTOR Constructors
ElementType.PACKAGE Package
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.
Note : If we don’t specify any @Target annotation, then that will be applicable for all
elements.
@Retention
RUNTIME
CLASS
SOURCE
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
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. }
1. @Retention({RetentionPolicy.SOURCE,RetentionPolicy.RUNTIME})
2. // (OR)
3. @Retention(value=RetentionPolicy.SOURCE)
4. @Retention(value=RetentionPolicy.RUNTIME)
5. Public @interface MyAnnotation{
6. }
1. @Retention(RetentionPolicy.RUNTIME)
2. Public @interface MyAnnotation{
3. }
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
Standard Annotations
@Override
The two most commonly made mistakes which are never detected by the java
compiler are
this will result in the sub class method can not be treated as overriding method
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. }
@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.
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
@SuppressWarnings
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
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
Enum types
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.
private Color(int c) {
code = c;
}
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();
}
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
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.
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.
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
Example Usage
Example Usage
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
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
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();
}
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. }
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.
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.
1. init()
2. process()
@SupportedAnnotationTypes(“*”)
@SupportedSourceVersion(SouceVersion.RELEASE_6)
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. }
Compile Note.java,
C:\>NoteAnnotationProcessor.java
Compile Demo.java as
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
VIDVAAN Technologies, Beside Sindhu Travels, Near S.R.Nagar Bus Stop, S.R.Nagar, Hyderabad-500038,
Ph: 040-64443399, www.vidvaanit.com
Page 25