Java Annotations Tutorials and custom annotations

Source: Internet
Author: User
Tags deprecated

Java annotations provide information about the code and have no direct impact on the code they annotate. In this tutorial, we'll learn about Java annotations, how to customize annotations, annotate usage, and how to use reflection to parse annotations.

Java annotations are referenced in Java1.5 and are widely used in some Java frameworks such as hibernate,jersey,spring. Annotations are metadata for programs that are embedded in the program itself. It can be parsed by the annotation parsing tool or compiler. We can also specify the life cycle of annotations, or only available during compilation or until run time.

Before we introduce annotations, we can get the program's metadata through program annotations or Java documents, but the annotations provide more. It contains not only the metadata but also its ability to determine whether it is available and the annotation parser can use it to control the processing flow.

Create custom annotations in Java

Creating custom annotations is similar to writing an interface with an @ symbol in addition to the interface keyword for annotations. We can declare the method in the annotations. Let's look at an example of an annotation and then discuss its characteristics.

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 ();}

Annotation methods cannot have parameters.

The return value type of the annotation method is limited to the base type, string,enums,annotation, or a combination of the above.

The annotation method can have a default value.

Annotations can append metadata. Meta-Annotations can provide information about this annotation.

Four types of meta-annotations:

[email protected] that elements using this annotation should is documented by Javadoc and similar tools. This type should is used to annotate the declarations of types whose annotations affect the use of annotated elements by T Heir clients. If a type declaration is annotated with documented, it annotations become part of the public API of the annotated element S.

[Email Protected]–indicates the kinds of program element to which a annotation type is applicable. Some possible values are TYPE, METHOD, CONSTRUCTOR, FIELD etc. If Target meta-annotation is not present and then annotation can be used on any program element.

[email protected]–indicates that a annotation type is automatically inherited. If user queries the annotation type on a class declaration, and the class declaration have no annotation for this type, the n the class ' s superclass would automatically is queried for the annotation type. This process would be repeated until a annotation for this type was found, or the top of the class hierarchy (Object) is re ached.

[Email protected]–indicates How long annotations with the annotated type is is retained. It takes retentionpolicy argument whose Possible values are SOURCE, CLASS and RUNTIME

Java built-in annotationsJava provides three built-in annotations:[Email protected] when we want to rewrite a method of the parent class, we should use this annotation to tell the compiler that we have rewritten this method. So when this method of the parent class is removed or changed, the compiler will make an error.[Email protected] we should have this annotation when we want the compiler to know that a method is obsolete. Java recommends that the reason for this method to become obsolete and its alternatives be written in the Java documentation.[Email protected] This is only used to tell the compiler to ignore the specific warnings that are generated, such as using primitive types in generics. Its retention policy is source, so it will be discarded by the compiler.Let's take a look at one example of using Java built-in annotations and the one we've customized 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 () {return ' overriden tostring Method ';} @Deprecated @methodinfo (comments = ' Deprecated method ', date = ' Nov ') public static void Oldmethod () {System.out.pri Ntln (' old method, don ' t use it. ');} @SuppressWarnings ({' Unchecked ', ' deprecation ') @MethodInfo (author = ' Pankaj ', comments = ' Main method ', date = ' Nov 17 2 012 ', revision = ten) public static void Genericstest () throws FileNotFoundException {List L = new ArrayList (); L.add (' abc '); Oldmethod ();}}

I believe this example can be seen by everyone, and it shows us the use of annotations in different contexts.

Java Annotation Parsing

We will use reflection to parse the main solution from a class. Note that the retention policy of the annotation must be runtime, otherwise its information will be invalidated at run time and we will not get any information.

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:AnnotationParsing.class.getClas Sloader (). LoadClass ((' com.journaldev.annotations.AnnotationExample ')). GetMethods ()) {//checks if MethodInfo Annotation is present for the METHODIF (Method.isannotationpresent (Com.journaldev.annotations.MethodInfo.class)) {try {//Iterates all the annotations available in the Methodfor (Annotation anno:method.getDeclaredAnnotations ()) {System.ou T.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 ();}}}

The output of the above program is:

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) method with 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) 

Java Annotations Tutorials and custom annotations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.