Brief analysis of Java annotations annotation

Source: Internet
Author: User
Tags deprecated

1. Overview

Java in the 1.5 version of the introduction of annotations annotation, also known as Java annotations, annotations are a syntax metadata, can be used directly into the source code, class/Method/variable/parameter/package name can be annotated. JavadocUnlike labels, the compiler retains the annotation code when it generates the class file, and it may be possible to use annotations while the program is running (run-time), allowing the Java virtual opportunity to retain annotations so that information about the annotations annotation can be obtained through reflection.

2. Built-in annotations

In fact, we will often meet annotations, such as, and @Override @Deprecated so on, these are the JDK built-in annotations, first look at the Java built-in annotations are mainly.

  • Annotations that act on Java code
    • @Override checks whether a method is a replication method, and if the method is not found in the parent class or the implemented interface, the compilation will fail.
    • @Deprecated tag a method or class is discarded, and if the class or method is used, the build process will report a warning
    • @SuppressWarnings notifies the compiler to ignore warnings about parameters that are being labeled
    • @SafeVarargs ignore warnings about calling methods or constructors that contain generic parameters, 1.7 new annotations
    • @FunctionalInterface indicates that one of the declared interfaces will be used as a functional interface, 1.8 new annotations

  • Annotations in other annotations, referred to as meta-annotations (meta Annotation)
    • @Retention indicate when the annotated annotations are used (that is, when the annotations are retained)
      • Keep only in source code, discard during compilation (retentionpolicy.runtime)
      • Annotations are saved to the class file during compilation and ignored when the class file is loaded (Retentionpolicy.class)
      • Annotations are read when the class file is loaded, that is, the annotations available in the run, and the annotations can be obtained by reflection (Retentionpolicy.runtime)
    • @Documented indicates that annotations that are annotated will be written to the Javadoc document when the Javadoc is generated
    • @Target indicate the scope of the annotated annotation
      • Elementtype.type: Used to describe classes, interfaces (including annotation types), or enum declarations
      • Elementtype.field: Used to describe a domain
      • Elementtype.method: Used to describe a method
      • Elementtype.parameter: Used to describe parameters
      • Elementtype.constructor: Used to describe the constructor
      • Elementtype.local_variable: Used to describe local variables
      • Elementtype.annotation_type: Used to describe annotations
      • Elementtype.package: Used to describe the package
    • @Inherited indicates that the annotated annotation is inherited, that is, if a @inherited-modified annotation type is used for a class, the annotation will also be used for the subclass of the class being modified.
    • @Repeatable indicates that annotated annotations can be used more than once for the same object, 1.9 new annotations
3. Custom annotations

It says so many annotations, we focus on meta-annotations, and when we customize annotations, we usually use meta-annotations to help us. The custom annotation format public @interface 注解名 {定义体} automatically inherits the Java.lang.annotation.Annotation interface when using @interface custom annotations. When customizing annotations, you cannot inherit other annotations or interfaces. The method declared in the annotation actually declares an annotation parameter, the name of the method is the name of the parameter, the return value type is the type of the parameter, and the default value of the parameter can be declared by default.

Custom annotations are simple to use @interface to define an annotation, as follows.

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Documentedpublic @interface ClassInfo {    default"Wang";    String date();    String comments();}

A custom annotation named ClassInfo , according to the @Retention note will always exist, that is, when the program is running, this annotation is still valid, @Target(ElementType.TYPE) indicating that ClassInfo the annotation is acting on the class, interface or enum declaration; @Documented
ClassInfo The information can be written to the Javadoc document.

Take a look at some of the annotation parameters in the custom annotations, there are three annotation parameters, note parameters can be set default values, such as author annotation parameters, the default value is Wang , the other two parameters have no default value.

Then look at another custom annotation.

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface MethodInfo {    default"No Description";    String date();}

This custom annotation MethodInfo is applied to the method, which is also present when the program is running, with two annotation parameters.

The definition of the annotation parameter (the definition of a method) can only be used with public or default two access modifiers, and the type of the parameter supports the following.

    • Eight basic data types (Byte,int,short,long,float,double,char,boolean)
    • String type
    • Class type
    • Enum type
    • Annotation type
    • Arrays of all types above
4. Use of annotations

In addition to the above two annotations, a field-scoped annotation is added.

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)public @interface FieldInfo {    String type();    String name();}

Note Parameters in custom annotations If you do not declare a default value, you must assign values to these parameters when using custom annotations, or the compiler will give an error.

Take a look at the code used by the annotations:

@ClassInfo(Author ="Wang", date ="2016/9/13", comments ="Annotation Demo") Public  class annotationdemo {    @FieldInfo(type ="Public", name ="Firstfield") Public intFirstfield;@FieldInfo(type ="Private", name ="Secondfield")PrivateString Secondfield;@MethodInfo(Description ="method in Annotationdemo", name ="FirstMethod") Public void FirstMethod(String value) {System.out.printf ("First method involved"); }@MethodInfo(Description ="method in Annotationdemo", name="Secondmethod")Private void Secondmethod() {System.out.printf ("First method involved"); }}
5. Get annotation Information

To get the annotation information, the first thing is to ensure that the annotations are present at the time the program runs, so it is common to add meta annotations to the custom annotations, so that during the process of the @Retention(RetentionPolicy.RUNTIME) program, we can get some annotation information through reflection, and see this article for a description of the reflection.

 Public  class annotationtest {     Public Static void Main(string[] args)        {Resolveclassannotationinfo (Annotationdemo.class);        Resolvefieldannotationinfo (Annotationdemo.class);    Resolvemethodannotationinfo (Annotationdemo.class); }Private Static void Resolveclassannotationinfo(class<?> CLZ) {//Determine if the class has ClassInfo annotations        if(Clz.isannotationpresent (Classinfo.class))            {ClassInfo ClassInfo = (ClassInfo) clz.getannotation (Classinfo.class); System.out.println (Classinfo.author () +" "+ classinfo.comments () +" "+ classinfo.date ()); }    }Private Static void Resolvefieldannotationinfo(class<?> CLZ) {field[] fields = Clz.getdeclaredfields (); for(Field field:fields) {if(Field.isannotationpresent (Fieldinfo.class))                {FieldInfo FieldInfo = (FieldInfo) field.getannotation (Fieldinfo.class); System.out.println (Fieldinfo.type () +" "+ Fieldinfo.name ()); }        }    }Private Static void Resolvemethodannotationinfo(class<?> CLZ) {method[] methods = Clz.getdeclaredmethods (); for(Method method:methods) {if(Method.isannotationpresent (Methodinfo.class))                {MethodInfo MethodInfo = (MethodInfo) method.getannotation (Methodinfo.class); System.out.println (Methodinfo.name () +" "+ methodinfo.description ()); }        }    }}

Through the reflection gets the Field/method in the class and so on, through getAnnotation() or getAnnotations() obtains the related annotation, obtains the concrete annotation to obtain the concrete information.

The output of the run result is as follows:


Figure 1 Running results Figure 6. Summarize

Java for beginners and even have some experience of Java developers, Java annotations may be less contact, and in practice, and rarely use annotations, but will often be seen in the code, this article is a simple introduction to the annotations, at least at the code level is read stress-free.

Java Annotations Annotation Analysis

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.