Module4 Annotations
Module4 Annotations
Module4 Annotations
Annotations
Definition: “Java Annotations are Metadata. Metadata is information about our source code, although they are
not a part of the program itself.”
Java annotations were added to Java from Java 5 and same continue in the updated version also.
Annotation can be applied to the class, interface, methods, method parameters, local variables or
fields’ variables to indicate some additional information which can be used by java compiler and JVM.
Compiler instructions: There are three built-in annotations available in Java (@Deprecated, @Override &
@SuppressWarnings) that can be used for giving certain instructions to the compiler.
Build-time instructions: Annotations can be used at build-time that can be further used by software build
tools for generating code, XML files etc.
Runtime instructions: We can define annotations to be available at runtime which we can access using
java reflection and can be used to give instructions to the program at runtime.
Annotation Basics
Its simplest form looks like the following:
Syntax: @Entity
Where @ character indicates to the compiler that this is an annotation.
The name following @ character is the name of the annotation.
In the above form, the annotation name is Entity.
Example:
@Entity(elements): A Java annotation can have elements for which you can set values.
@Entity(tableName = "vehicles"): An elements are like an attribute or parameter which
is enclosed inside the parentheses after the annotation name. Here, it contains a single element named
tableName, with the value set to vehicles.
@Entity(tableName = "vehicles", primaryKey = "id"):An annotation can contain
multiple elements.
Module4 Annotations
2.1 Types of Built-in Annotations
Java defines seven types of annotations, some annotations are applied to Java code and some to custom
annotation as listed below.
4 Built-in Annotations used in custom annotation 3 Built-in Annotations used in Java code and
and imported from java.lang.annotation: imported from java.lang:
i. @Retention a. @Override
ii. @Documented b. @Deprecated
iii. @Target c. @SuppressWarnings
iv. @Inherited
@Deprecated
The @Deprecated annotation is used to mark a class, method or field as deprecated, and should no
longer be used.
Syntax: The compiler generates a warning whenever a
@Deprecated program uses a method, class, or field with the
void myMethod(){ @Deprecated annotation.
System.out.println("hello"); When an element is deprecated, it should also be
} documented using the Javadoc @deprecated tag,
Example-3.2.1:
class A{ public class AnnotationDemo {
void normal(){ public static void main(String[] args)
System.out.println("hello"); {
} A a=new A();
@Deprecated a.deprMethod();
void deprMethod(){ }
System.out.println("hello"); }
}
}
@Override
The @Overrride annotation is used to say to the compiler we are overriding an existing method.
Syntax: @Override annotation assures that the subclass
@Override method is overriding the super class method.
void myMethod(){ If the compiler finds that there is no matching method
System.out.println("hello"); found in super class then generates a warning.
}
This is not mandatory to use @Override.
Module4 Annotations
Example-3.2.2:
class Animal{
void eatSomething(){
System.out.println("eating public class OverrideTest {
something"); public static void main(String
}
} args[]){
class Dog extends Animal{ Animal a=new Dog();
@Override a.eatSomething();
void eatSomething(){ }
//should be eatSomething }
System.out.println("eating foods");
}
}
@SupressWarnings
The @SuppressWarnings annotation is used to suppress warnings issued by the compiler.
Syntax:
@SuppressWarnings(parameters) @SuppressWarnings(“parameter”)
void myMethod(){
System.out.println("hello"); @SuppressWarnings( { “parameter”, “parameter” } )
}
The @SuppressWarnings annotation makes the compiler suppress warnings for a given method.
Example-3.2.3: If a method calls a deprecated method, or makes an insecure typecast, the compiler may
generate a warning. You can suppress these
import java.util.*;
warnings by annotating the method
public class SuppressTest {
containing the code with the
public static void main(String[] args){
@SuppressWarnings annotation.
List data = new ArrayList();
// this causes unchecked warning
data.add("hello");data.add("world");
Iterator it = data.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Module4 Annotations
In the above example, compiler throw the unchecked warning when the following statement encountered.
List data = new ArrayList();
import java.util.*; To avoid this warning add
public class SuppressTest { @SuppressWarnings annotation in the
program.
@SuppressWarnings("unchecked")
public static void main(String[] args){
List data = new ArrayList();
// this causes unchecked warning
data.add("hello");
data.add("world");
Iterator it = data.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
@Documented:
The @Documented annotation is a marker annotation that tells a Java tool that an annotation is to be
documented. It is designed to be used only as an annotation to an annotation declaration.
Example:
import java.lang.annotation.Documented; When generating JavaDoc for the
MySuperClass class, the
@Documented
public @interface MyAnnotation { - - - - } @MyAnnotation is now included in the
JavaDoc. You will not use the
@MyAnnotation
@Documented annotation often, but now
public class MySuperClass { - - - - - }
you know it exists if you should need it.
@Target:
The @Target tag is used to specify at which type, the annotation is used.
The @Target takes one argument, which must be constant from the ElementType enumeration
[java.lang.annotation.ElementType]. This argument specifies the type of declarations to which the
annotation can be applied.
Possible constant values for ElementType are listed below:
Element Type Can be applied to Element Type Can be applied to
@Retention
The @Retention annotation is used to specify to what level annotation will be available. There are three
such policies within the java.lang.annotation.RetentionPolicy.
You can specify for your custom annotation if it should be available at runtime, for inspection via
reflection. You do so by annotating your annotation definition with the @Retention annotation. Here is
how that is done.
RetentionPolicy Availability
refers to the source code, discarded during compilation. So it will not be
SOURCE
available in the compiled class.
refers to the .class file, available to java compiler but not to JVM. It is included
CLASS
in the class file.
RUNTIME refers to the runtime, available to Java compiler and JVM.
Example:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
int value1();
String value2();
}
@Inherited
@Inherited is a marker annotation that can be used only on annotation declaration. The @Inherited
annotation marks the annotation to be inherited to subclasses. By default, annotations are not inherited to
subclasses.
Example:
In this example, the class MySubClass inherits the annotation @ForEveryone because MySubClass
inherits from MySuperClass, and MySuperClass has a @ForEveryone annotation.
Module4 Annotations
2.2 Creating Your Own Annotations
It is possible to create your own (custom) Java annotations. Annotations are defined in their own file, just like
a Java class or interface that as shown below.
Example:
Syntax: @interface <MyAnnotationName>{ @interface <MyAnnotation> {
String value();
data_type1 var_name1;
String name();
data_type2 var_name2;
int age();
data_type3 var_name3;
String[] newNames();
}
}
Where, the @interface keyword indicates to the Java compiler that this is a Java annotation definition.
<MyAnnotationName> is a name of the annotation.
Notice that each element is defined similarly to a method definition in an interface. It has a data type
and a name. You can use all primitive data types as element data types.
You can also use arrays as a data type but cannot use complex objects as a data type.
To use the above @MyAnnotation annotation, you could use code like this:
@MyAnnotation(value="123",name="Jakob", age=37,
newNames={"Jenkov", "Peterson"})
public class MyClass { - - - - - - - - - - }
As you can see, I have to specify values for all elements of the @MyAnnotation annotation.
Element or member Default Values:
You can specify default values for an element. That way the element becomes optional and can be left out.
Example:
The value element can now be left out when using the annotation. If you leave it out, it will be considered as
if you had used the default value for the value element.
The above annotation applied to the class MyClass with an element value left out, so that element is set to
the default value that shown below:
import java.lang.annotation.*;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno{}
}
catch(NoSuchMethodException e){
System.out.println("Method not Found");
}
}
public static void main(String[] args){
Method1();
}
}
A single - value annotation contains only one member and it works like a normal annotation.
We only need to specify the value for the member, when only one member is present, you don’t need to
specify the name of the member.
Syntax:
@interface MyAnnotation { We can provide the default value also.
int value(); @interface MyAnnotation{
} int value() default 0;
}
Module4 Annotations
Example – 3.2.5: Here, @MyAnno1 annotation have one member which is used to annotate sayHello() as
@MyAnno1(100). Notice the way a value is inserted.
import java.lang.annotation.*;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnno1{
int value() default 0;
}
if(mt.isAnnotationPresent(MyAnno1.class)){
System.out.println("Single is Present");
System.out.println("Value is: " + sng.value());
}
else
System.out.println("Not Present");
}
catch(NoSuchMethodException e){
System.out.println("Method not Found");
}
}
public static void main(String[] args){
sayHello();
}
}