Java annotation tutorial and custom Annotation

Source: Internet
Author: User

Java annotation tutorial and custom Annotation

Java annotations provide information about the code and have no direct impact on the Code Annotated with them. In this tutorial, we will learn Java annotations, how to customize annotations, how to use annotations, and how to use reflection parsing annotations.

Java annotations are referenced in Java and are widely used in some Java frameworks such as Hibernate, Jersey, and Spring. Annotation is the metadata of the program embedded in the program itself. It can be parsed by annotation parsing tools or compilers. We can also specify the annotation life cycle, or it is only available during compilation or until running.

Before the annotation is introduced, we can obtain the program metadata through the program annotation or Java document, but the annotation provides more. It not only contains metadata, but also determines whether it is available and the annotation parser can use it to control stream processing.

Create a custom annotation in Java

Creating a custom annotation is similar to writing an interface, except that an @ symbol is added before the annotation interface keyword. We can declare a method in the annotation. Let's look at an annotation example and discuss its 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 cannot have parameters.

The Return Value Type of the Annotation method is limited to the basic type, String, Enums, Annotation, or the preceding combination.

The annotation method can have default values.

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

Four meta Annotations:

1. @ incluented-indicates that elements using this annotation shocould be used ented by javadoc and similar tools. this type shoshould be used to annotate the declarations of types whose annotations affect the use of annotated elements by their clients. if a type declaration is annotated with specified ented, its annotations become part of the public API of the annotated elements.

2. @ Target-indicates the kinds of program element to which an annotation type is applicable. some possible values are TYPE, METHOD, CONSTRUCTOR, FIELD etc. if Target meta-annotation is not present, then annotation can be used on any program element.

3. @ Inherited-indicates that an annotation type is automatically inherited. if user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class's superclass will automatically be queried for the annotation type. this process will be repeated until an annotation for this type is found, or the top of the class hierarchy (Object) is reached.

4. @ Retention-indicates how long annotations with the annotated type are to be retained. It takes RetentionPolicy argument whose Possible values are SOURCE, CLASS and RUNTIME

Java built-in annotation Java provides three built-in Annotations: 1. @ Override-when we want to Override a method of the parent class, we should use this annotation to tell the compiler that we have rewritten this method. Therefore, the compiler reports an error when this method of the parent class is removed or changed. 2. @ Deprecated-This annotation should be used when we want the compiler to know that a method has passed. Java recommends that you write the reasons for this method's expiration and its alternative solutions in the Java document. 3. @ SuppressWarnings-this is only used to tell the compiler to ignore specific warnings, such as using the original type in generics. Its retention policy is SOURCE, so it will be discarded by the compiler. Let's take a look at an example of using the built-in Java annotation and the annotation we defined 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 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 everyone can understand this example. It shows us how to use annotations in different situations.

Java annotation Parsing

We will use reflection to parse the primary solution from a class. Note that the Retention policy of the annotation must be RUNTIME; otherwise, its information will be invalid at RUNTIME 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.getClassLoader().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.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:

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)

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.