Annotations are the information that can be treated as supplement about the program. It is used to associate with the meta data. Generally, it contains the information about classes, methods, constructors, variables and so on…
Syntax:
@Annotation_Information
Eg: @FunctionalInterface
Built in
package for annotation is java.lang.annotation
Where to use annotations??
Mainly, annotations are used in
declaration. It can declare a class, member functions, variables and so on. In
java8, it deals with types. So, it is called Type annotations.
Type
annotations are very useful in object creation, type casting an element,
implements and thrown statements.
Some of the
examples are given below.
1. Object creation:
This is used to create an object for a class.
Eg:
new @Class1 Obj(); where new is the keyword to create an object. @Class1
is the class. Obj() is the object name.
2. Type casting:
It is the process of converting one
datatype to another.
Eg: a = (@NonNull int) b;
3. Using thrown:
Thrown is an exception. This can be
implemented by as follows.
Eg: void SampleMethod() throws
@Critical MethodException()
{
---------------
}
4. Using Implements:
“Implements” is one of the
clause used in java.
Eg: class SampleList<L> implements
@ReadOnly List<@Readonly
L>
{
…………
}
These are the ways of type
annotations are used.
Now, a java program to illustrate type
annotation is given below.
Java
program to illustrate Type Annotation:
This java program has following
steps to implement the type annotation.
Steps:
- As a beginning of the program, include the built in packages.
- Create a type annotation @Target.
- Implement it using an interface @interface.
- Create a public class TypeAnnotationEg and save it.
- Inside the main function, create a type annotation with a string str. Displays the message as “It is a type annotation example” using system.out.println.
- Call the Msg() function.
- Inside the Msg(), print the message.
//Java
program to illustrate type annotation
import
java.lang.annotation.ElementType;
import
java.lang.annotation.Target;
@Target(ElementType.TYPE_USE)
@interface
TypeAnnoIf{}
public
class TypeAnnotationEg {
public static void main(String[]
args) {
@TypeAnnoDemo
String str = "It is a type annotation example";
System.out.println(str);
Msg();
}
static @TypeAnnoIf int Msg() {
System.out.println("The return
data is annotated");
return 0;
}
}
Compile and
run the program to print the output.
C:\raji\blog>javac
TypeAnnotationEg.java
C:\raji\blog>java
TypeAnnotationEg
It is a
type annotation example
The return
data is annotated
No comments:
Post a Comment