The Java annotation provides some information about the code, but does not directly affect the content of the code it notes. In this tutorial, we will learn Java annotations, how to customize annotations, the use of annotations, and how to parse annotations through reflection.
Java1.5 introduces annotations, and many of the current Java frameworks use annotations such as Hibernate, Jersey, and Spring. Annotations are embedded in the program as metadata for the program. Annotations can be parsed by some parsing tools or by a compilation tool. We can also declare annotations to be useful during compilation or execution.
Before using annotations, the program source data is only through Java annotations and Javadoc, but annotations provide far more functionality than these. Annotations not only contain metadata, it can also be used in the process of running a program, the annotation interpreter can determine the order of execution of the program through the annotation. For example, in Jersey WebService we add the **path** annotation in the form of a URI string to the method, the Jerser interpreter will determine the method to invoke the given URI as the program runs.
Create Java Custom annotations
Creating a custom annotation is similar to creating an interface, but the interface keyword of the annotation needs to begin with the @ symbol. We can declare methods for annotations. Let's take a look at the annotation example, and then we'll discuss some of his features.
Package com.journaldev.annotations;
Import java.lang.annotation.Documented;
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Inherited;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;
@Documented
@Target (elementtype.method)
@Inherited
@Retention (retentionpolicy.runtime)
Public @interface methodinfo{
String author () default ' Pankaj ';
String date ();
int revision () default 1;
String comments ();
}
The annotation method can not carry parameters;
The annotation method return value type is limited to: base type, String, Enums, annotation, or arrays of these types;
The annotation method can have a default value;
Annotations themselves can contain meta annotations, which are used to annotate other annotations.
Here are four kinds of meta annotations :
1. @Documented -Indicates that the element that owns this annotation can be documented by Javadoc tools of this type. This type should be used to annotate types that affect the customer's use of annotated element declarations. If a declaration is annotated using documented, this type of annotation is used as the public API for the annotated program member.
2. @Target--Indicates the scope of the program element to which the annotation of this type can be annotated. The value of this meta annotation can be type,method,constructor,field and so on. If the target meta annotation does not appear, then the defined annotation can be applied to any element of the program.
3. @Inherited--Indicates that the annotation type is automatically inherited. If the user queries the meta annotation type in the current class and the current class declaration does not contain the meta annotation type, it will also automatically query whether the parent class of the current class has a inherited annotation, which will be repeated to know if the annotation type is found, or to query the top-level parent class.
4. @Retention-Indicates the length of time the annotation has been retained. Retentionpolicy value is source,class,runtime.
Java Built in annotations
Java provides three kinds of built-in annotations.
1. @Override-When we want to make a copy of a method in the parent class, we need to use that annotation to tell the compiler that we want to overwrite this method. This enables the compiler to prompt for an error message when the method in the parent class is removed or changes occur.
2. @Deprecated-We should use this annotation when we want the compiler to know that a method is not recommended for use. Java is recommended for use in Javadoc, and we should provide a way to explain why this method is not recommended for use and alternatives.
3. @SuppressWarnings-This simply tells the compiler to ignore specific warning messages, such as using native data types in generics. Its retention policy is source, which is valid in the source file, and discarded by the compiler.
Let's take a look at a Java built-in annotation example to refer to the custom annotation mentioned above.
Package com.journaldev.annotations;
Import java.io.FileNotFoundException;
Import java.util.ArrayList;
Import java.util.List;
public class Annotationexample {public
static void Main (string[] args) {
}
@Override
@MethodInfo ( Author = ' Pankaj ', comments = ' Main method ', date = ' Nov ', revision = 1) public
String toString () {
retur N ' overriden toString method ';
}
@Deprecated
@MethodInfo (comments = ' deprecated method ', date = ' Nov ') public
static void Oldmethod () {
system.out.println (' old method, don ' t use it. ');
}
@SuppressWarnings ({' Unchecked ', ' deprecation '})
@MethodInfo (author = ' Pankaj ', comments = ' Main method ', date = ' No ' V ', revision = ten) public
static void Genericstest () throws FileNotFoundException {
List l = new Arrayli St ();
L.add (' abc ');
Oldmethod ();
}
Believe this example can be self-evident and can show the application in different scenarios.
Java Annotation Parsing
We will use reflection techniques to parse the annotations of Java classes. The annotation retentionpolicy should be set to runtime otherwise the annotation information for the Java class will not be available during execution so we cannot get any data related to the annotation from it.
Package com.journaldev.annotations;
Import java.lang.annotation.Annotation;
Import Java.lang.reflect.Method; public class Annotationparsing {public static void main (string[] args) {try {-for-method Method:annotationparsi Ng.class. getClassLoader (). LoadClass ((' com.journaldev.annotations.AnnotationExample ')). GetMethods ()) {/ /checks if MethodInfo annotation is present for the "method if" (Method.isannotationpresent. Methodinfo.class)) {try {//iterates all of the annotations available in the (Annotation anno
: Method.getdeclaredannotations ()) {System.out.println (' Annotation in method ' + method + ': ' + anno);
} MethodInfo Methodanno = Method.getannotation (Methodinfo.class);
if (methodanno.revision () = = 1) {System.out.println (' method with revision no. 1 = ' + method ');
} catch (Throwable ex) {ex.printstacktrace (); catch (SecurityException |
ClassNotFoundException e) {e.printstacktrace (); }
}
}
Run the above program to output:
Annotation in method ' public java.lang.String com.journaldev.annotations.AnnotationExample.toString () ': @ Com.journaldev.annotations.MethodInfo (Author=pankaj, Revision=1, Comments=main method, Date=nov) Revision No 1 = public java.lang.String com.journaldev.annotations.AnnotationExample.toString () Annotation in method ' public static void Com.journaldev.annotations.AnnotationExample.oldMethod () ": @java. lang.deprecated () Annotation in Method ' public static void Com.journaldev.annotations.AnnotationExample.oldMethod () ': @ Com.journaldev.annotations.MethodInfo (Author=pankaj, Revision=1, comments=deprecated method, Date=nov) method With revision no. 1 = public static void Com.journaldev.annotations.AnnotationExample.oldMethod () Annotation in method ' pub Lic static void Com.journaldev.annotations.AnnotationExample.genericsTest () throws Java.io.FileNotFoundException ': @ Com.journaldev.annotations.MethodInfo (Author=pankaj, revision=10, Comments=main method, Date=nov 17 2012)
This is the whole story of the tutorial, and hopefully you'll learn something from it.