Java Basics-Annotations

Source: Internet
Author: User
Tags deprecated throw exception java se

A comment is a form of metadata that provides data that is not the program itself, and comments have no direct effect on the commented code.

This article summarizes the use of annotations, the Java Platform (SE) predefined annotations, type annotations that are used with pluggable type systems to achieve stronger type checking, and how to implement duplicate annotations.

Annotations have many uses, including:

    • Provide information to the compiler-the compiler can use annotations to check for errors or suppress warning messages
    • Compile-time or deploy-time processing-software tools can process comments and generate code, XML files, and more
    • Run-time processing-some annotations can be detected at run time
Comment Format

The simplest form of annotations is as follows:

@Entity

@ symbol prompt compiler The next word is a comment, the example is an entity, the annotation can contain elements, the element can be named or unnamed, if there is only one element in the comment, the element name can be omitted, if the comment does not contain elements, the parentheses can be omitted, You can use more than one comment in a declaration, and you can allow multiple comments with the same name in Java8, also called repeating comments:

// include elements in comments @Author (   = "Benjamin Franklin",   = "3/27/2003")class//  There is only one element in the note, the name can be omitted @SuppressWarnings ("Unchecked")void  MyMethod () {...} // }
Note Where to use

Annotations can be applied to declarations, including classes, fields, methods, and other declarations that become elements. In general, each comment occupies one line.

After java8, annotations can also be applied when the type is used, as follows:

// class instance Bed        frame expression New @Interned MyObject (); // Type Conversions        myString = (@NonNull String) str; // implementing a phrase        class Implements             @Readonly List< @Readonly t> {...} // Throw Exception declaration        void throws             @Critical temperatureexception {...}

The form of all annotations is called a type comment.

Declaration notes

Examples of declarations for annotations:

@Interface  classpreamble {   String author ();   String date ();
int currentrevision () default 1;
}

The definition of a comment is similar to an interface, except that the interface keyword has an @ symbol before it, in fact the annotation type is a form interface, the body definition of the comment contains the element declaration of the annotation, the element can have a default value, and the method of adding the default value is to follow the default keyword and its defaults after the element declaration. As shown in the example above.

predefined annotation types

Several annotation types are predefined in the Java SE API, some of which are used by Java compilers, and some are applied with other annotations.

Comments used by the Java language

The predefined annotation types in the Java.lang package are @deprecated, @Override, and supresswarning.

@Deprecated hints that the annotated element is deprecated and should not be used again. The compiler generates a warning message when a method, class, or field that is annotated by the @deprecated annotation is used. When deciding to discard an element, it should also be reflected in the Javadoc, using Javadoc's @deprecated tag, as shown in the following example, the Javadoc tag begins with a lowercase letter:

   // Javadoc Write Javadoc note here    /** @deprecated * Explanation of why      It is deprecated      */           @Deprecated    staticvoid  Deprecatedmethod () {}}

@Override comment Notifies the compiler that the method commented by the comment will overwrite the method in the parent class, and of course, the overwrite method does not need to use the @override comment, @Override the use of the comment can reduce the error, such as a misspelling of the method name, and the compiler will produce an error if the method is not successfully overwrite.

@SuppressWarnings Note The compiler suppresses the generation of specified error messages, each of which is of one type, and two error messages are listed in the Java language Specification: deprecation and unchecked.

  @ Safevarargs (Java7 and later) comments applied to methods or constructors, when using annotations, methods or constructors that contain mutable variables will not produce unchecked warning messages because of potentially unsafe operations on mutable variables.

  @ Functionalinterface annotations are introduced in JAVA8 and use this comment to indicate that the annotated interface is a functional interface.

Comments used by other annotations

Comments that are used for other annotations are called meta-annotations (meta-annotations), and there are multiple meta-comments in java.lang.annotation.

  @Retention Note Specifies how to store comments for a tag:

    • RetentionPolicy.SOURCE– Annotated annotations are only kept at the source code level, ignored by the compiler
    • RetentionPolicy.CLASS– Annotated annotations are preserved at compile time, but are ignored by the Java Virtual machine
    • RetentionPolicy.RUNTIME– Annotated annotations are retained in the Java Virtual machine, but are ignored at run time

  @Documented Note the note you specify should also use the Javadoc tool to compose the document when you use it.

  @Target Comment The object used to restrict the markup's comment, which specifies one of the following element types as its value:

    • ElementType.ANNOTATION_TYPECan be applied to a comment
    • ElementType.CONSTRUCTORCan be applied to a constructor
    • ElementType.FIELDCan be applied with a comment or attribute
    • ElementType.LOCAL_VARIABLECan be applied to a local variable
    • ElementType.METHODAnnotations that can be applied to the method layer
    • ElementType.PACKAGEcan be applied to package declarations
    • ElementType.PARAMETERParameters that can be applied to a method
    • ElementType.TYPECan be applied to a class

  The comment type of the @Inherited comment Prompt tag can be inherited from the superclass (default cannot inherit), and when the user does not retrieve the comment for that type, the comment is retrieved in its parent class, which can only be used in the declaration of the class.

@Repeatable annotations are introduced from JAVA8, and the type of the hint tag can be used more than once for the same element.

Type annotations and pluggable type systems

Java8 Previously, annotations could only be used in declarations, and after java8, annotations could be applied to any class where they were used, such as the creation expression (new) of the class instance, the conversion (cast), the implementation clause, and the throw clause (where the above comment has been used for example).

Common types of annotations can be used to support the analysis of improved type checking in Java programming. Java8 SE does not itself provide a framework for type checking, but you can either write or download a type-checking framework that is implemented by one or more modules that are used in conjunction with the Java compiler, such as the inspection Framework, checker framework, written by the University of Washington.

Retrieving comments

The Reflection API is used by multiple methods to retrieve comments, returning a single comment method, such as Annotatedelement.getannotationbytype (class<t>), whose behavior has not changed. After Java8, because a type of comment can be reused for compatibility reasons, duplicate comments are stored in a comment container and generated automatically by the Java compiler, so when there is a duplicate comment, you can first get a comment container for multiple comments so that the traditional method of returning a single comment can be used. Java8 also introduces a method that can return multiple annotations at once, such as AnnotatedeleMent.getannotations (class<t>).

Java Basics-Annotations

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.