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.

12345678910111213141516171819 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 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.

1234567891011121314151617181920212223242526272829303132 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 17 2012", revision = 1)    public String toString() {        return "Overriden toString method";    }    @Deprecated    @MethodInfo(comments = "deprecated method", date = "Nov 17 2012")    public static void oldMethod() {        System.out.println("old method, don‘t use it.");    }    @SuppressWarnings({ "unchecked", "deprecation" })    @MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 10)    public static void genericsTest() throws FileNotFoundException {        List l = new ArrayList();        l.add("abc");        oldMethod();    }}

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.

12345678910111213141516171819202122232425262728293031323334353637383940 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                    .getClassLoader()                    .loadClass(("com.journaldev.annotations.AnnotationExample"))                    .getMethods()) {                // checks if MethodInfo annotation is present for the method                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);                        }                        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:

123456 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 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 17 2012)Method with revision no 1 = public static void com.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

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.