Java Annotations Tutorial: Custom annotation examples, parsing with reflection

Source: Internet
Author: User
Tags deprecated

Java annotations provide information about the code and have no direct impact on the annotated code structure. In this tutorial, we'll learn about Java annotations, how to write custom annotations, how annotations are used, and how to use reflection to parse annotations.

Annotations are introduced in Java 1.5 and are now widely used in various Java frameworks, such as hibernate,jersey,spring. Annotations are equivalent to a metadata embedded in a program that can be parsed using the annotation resolution tool or compiler, or you can specify that annotations are valid at compile time or run time.

Before the annotations were born, the metadata of the program existed in the form of Java annotations or Javadoc, but annotations could provide more functionality, not only metadata, but also runtime, which the annotation parser could use to determine the processing flow. For example, in Jersey WebService, we add a path annotation and URI string to a method, and at run time, Jersey parses it and determines the method that acts on the specified URI pattern.

Create custom annotations in Java

Creating a custom annotation is similar to writing an interface, except that it has an @ sign before its interface keyword. We can define the method in the annotations, take a look at an example, and then we will continue to discuss its characteristics.

1  Packagecom.journaldev.annotations;2  3 Importjava.io.FileNotFoundException;4 Importjava.util.ArrayList;5 Importjava.util.List;6  7  Public classAnnotationexample {8  9      Public Static voidMain (string[] args) {Ten     } One   A @Override -@MethodInfo (author = "Pankaj", comments = "Main method", date = "Nov", Revision = 1) -      PublicString toString () { the         return"Overriden toString Method"; -     } -   - @Deprecated +@MethodInfo (comments = "Deprecated method", date = "Nov 17 2012") -      Public Static voidOldmethod () { +System.out.println ("Old method, don t use it.")); A     } at   -@SuppressWarnings ({"Unchecked", "deprecation" }) -@MethodInfo (author = "Pankaj", comments = "Main method", date = "Nov", Revision = 10) -      Public Static voidGenericstest ()throwsFileNotFoundException { -List L =NewArrayList (); -L.add ("abc")); in Oldmethod (); -     } to   +}

    • Annotation methods cannot have parameters.
    • The return type of the annotation method is limited to primitive types, strings, enumerations, annotations, or arrays of the above types.
    • The annotation method can contain default values.
    • Annotations can contain meta annotations that are bound to them, meta annotations provide information for annotations, and there are four types of meta-annotations:

1. @Documented – The element that uses the annotation should be documented by Javadoc or similar tools, applied to the type declaration, and the annotations of the type declaration affect the client's use of the annotation element. If a type declaration adds a documented annotation, its annotations become part of the public API of the annotated element.

2. @Target – Indicates the type of program element that supports annotations, some possible values are type, METHOD, CONSTRUCTOR, field, and so on. If the target element annotation does not exist, then the annotation can be used on top of any program element.

3. @Inherited – Indicates that an annotation type is automatically inherited, and if the user queries the annotation type at the time of the class declaration and there is no annotation of that type in the class declaration, the annotation type automatically queries the parent class of the class, and the process repeats until the type's annotations are found. Or arrive at the top level of the class structure (Object).

4. @Retention – Indicates the length of time the annotation type is retained, it receives the Retentionpolicy parameter, the possible values are source, CLASS, and runtime.

Java built-in annotations

Java provides 3 built-in annotations.

1. @Override – When we want to overwrite a method of the parent class, we need to use that note to tell the compiler that we are overriding a method. In this case, when the parent class method is deleted or modified, the compiler will prompt the error message. You can learn why we should always use Java overlay annotations When overriding a method.

2. @Deprecated – This annotation should be used when we want the compiler to know that a method has been deprecated (deprecate). Java recommends providing information in Javadoc to inform the user why this method has been deprecated and what the workaround is.

3. @SuppressWarnings – This note simply informs the compiler that ignoring them produces a special warning, such as the use of primitive types in Java generics. Its persistence strategy (retention policy) is source and will be discarded in the compiler.

Let's look at an example that shows how to use built-in annotations, as well as the custom annotations mentioned in the examples above.

1  Packagecom.journaldev.annotations;2  3 Importjava.io.FileNotFoundException;4 Importjava.util.ArrayList;5 Importjava.util.List;6  7  Public classAnnotationexample {8  9      Public Static voidMain (string[] args) {Ten     } One   A @Override -@MethodInfo (author = "Pankaj", comments = "Main method", date = "Nov", Revision = 1) -      PublicString toString () { the         return"Overriden toString Method"; -     } -   - @Deprecated +@MethodInfo (comments = "Deprecated method", date = "Nov 17 2012") -      Public Static voidOldmethod () { +System.out.println ("Old method, don t use it.")); A     } at   -@SuppressWarnings ({"Unchecked", "deprecation" }) -@MethodInfo (author = "Pankaj", comments = "Main method", date = "Nov", Revision = 10) -      Public Static voidGenericstest ()throwsFileNotFoundException { -List L =NewArrayList (); -L.add ("abc")); in Oldmethod (); -     } to   +}

I believe this example is very clear and shows how annotations are used in different scenarios.

Java Annotation Parsing

We will use the Java reflection mechanism to parse annotations from a class, keeping in mind that the annotation retention policy should be runtime, otherwise its information is invalid at run time and we cannot get any data from it.

1  Packagecom.journaldev.annotations;2  3 Importjava.lang.annotation.Annotation;4 ImportJava.lang.reflect.Method;5  6  Public classannotationparsing {7  8      Public Static voidMain (string[] args) {9         Try {Ten              for(Method method:annotationparsing.class One . getClassLoader () A. LoadClass ("Com.journaldev.annotations.AnnotationExample")) - . GetMethods ()) { -                 //checks if MethodInfo annotation is present for the method the                 if(Method -. isannotationpresent (Com.journaldev.annotations.MethodInfo.class)) { -                     Try { -                         //iterates all the annotations available in the method +                          for(Annotation anno:method.getDeclaredAnnotations ()) { -System.out.println ("Annotation in Method") ++ Method + "':" +anno); A                         } atMethodInfo Methodanno =Method -. getannotation (MethodInfo.class); -                         if(methodanno.revision () = = 1) { -System.out.println ("Method with revision No 1 =" -+method); -                         } in   -}Catch(Throwable ex) { to ex.printstacktrace (); +                     } -                 } the             } *}Catch(SecurityException |classnotfoundexception e) { $ e.printstacktrace ();Panax Notoginseng         } -     } the   +}

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 17 2012) Method with revision no1 = Publicjava.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 17 2012) Method with revision no1 = Public Static voidCom.journaldev.annotations.AnnotationExample.oldMethod () Annotation in Method' public 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)

The annotations API is very powerful and is widely used in various Java frameworks, such as Spring,hibernate,junit. You can see reflection in Java for more information.

This is all of the Java Annotations Tutorial, and I hope you can learn something from it.

Java Annotations Tutorial: Custom annotation examples, parsing with reflection

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.