Java basics-annotations and java Basics

Source: Internet
Author: User

Java basics-annotations and java Basics

Annotation is a form of metadata that provides non-program data and has no direct impact on the annotated code.

This article mainly summarizes the usage of comments. java platform (SE) pre-defined comments. Type comments are used with the pluggable type system for stronger type checks, and how to implement repeated comments.

Annotations have many functions, including:

  • Provide information for the compiler -- the compiler can use comments to check errors or suppress warning information
  • Processing during compilation or deployment-software tools can process comments and generate code, XML files, etc.
  • Runtime processing-Some Annotations can be detected during runtime
Comment format

The simplest form of annotation is as follows:

@Entity

@ Symbol indicates that the next word in the compiler is a comment. In this example, the comment is Entity. The comment can contain elements, and the element can be named or unnamed, if there is only one element in the annotation, the element name can be omitted. If the annotation does not contain any element, parentheses can be omitted. You can use multiple annotations in a declaration, java 8 allows multiple comments with the same name, also known as repeated comments:

// The annotation contains the element @ Author (name = "Benjamin Franklin", date = "3/27/2003") class MyClass () {// The annotation contains only one element, the name can be omitted @ SuppressWarnings ("unchecked") void myMethod (){...} //...}
Location used for Annotation

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

After Java 8, annotations can also be applied when types are used, as shown below:

// Type instance bed frame expression new @ Interned MyObject (); // type conversion myString = (@ NonNull String) str; // implement the phrase class UnmodifiableList <T> implements @ Readonly List <@ Readonly T> {...} // throw an exception declaration void monitorTemperature () throws @ Critical TemperatureException {...}

All annotations are called type annotations.

Declaration comment

Annotation declaration example:

@interface ClassPreamble {   String author();   String date();
 int currentRevision() default 1;
}

The annotation definition is similar to the interface, except that the interface keyword has the @ symbol before it. In fact, the annotation type is a form interface. The annotation subject definition contains the annotation element declaration, and the element can have a default value, to add a default value, follow the default keyword and default value after the element declaration, as shown in the preceding example.

Predefined annotation type

The java se API pre-defines multiple annotation types, some of which are used by the java compiler, and some are applications and other annotations.

Notes used in java

Pre-defined annotation types in the java. lang package include @ Deprecated, @ Override, and SupressWarning.

@ Deprecated indicates that the annotation element has been Deprecated and should not be used again. When a method, class, or field annotated by @ Deprecated is used, the compiler generates a warning message. When deciding to discard an element, it should also be reflected in javadoc. The javadoc @ deprecated tag is used, as shown in the following example. The javadoc tag starts with a lowercase letter:

// Javadoc write javadoc comments here/*** @ deprecated * explanation of why it was deprecated */@ Deprecated static void deprecatedMethod (){}}

 

@ Override annotation: the method used to notify the compiler that the annotation will overwrite the method in the parent class. Of course, the Override method does not need to be annotated with @ Override, @ Override annotation can reduce errors. For example, if the method name is misspelled, if the method is not successfully overwritten, the compiler will generate an error.

@ SuppressWarnings annotation notifies the compiler to suppress the generation of specified error messages. Each error message belongs to one type. Two error messages are listed in the java language manual: deprecation and unchecked.

  @SafeVarargs (java7 and later) annotations are applied to methods or constructors, methods or constructors that contain variable variables do not generate unchecked warnings for operations that may be insecure.

  @FunctionalInterface annotation is introduced in Java 8. This annotation indicates that the annotated interface is a functional interface.

Comments used for other comments

Annotations used for other annotations are called meta-annotations. java. lang. annotation contains multiple meta-annotations.

  @ RetentionNote:

  • RetentionPolicy.SOURCE-The annotation marked is only kept at the source code layer and ignored by the compiler.
  • RetentionPolicy.CLASS-The annotation marked is retained during compilation, but is ignored by the Java Virtual Machine.
  • RetentionPolicy.RUNTIME-The Marked comments are retained in the Java virtual machine, but are ignored during runtime.

  @ Brief entedThe annotation prompts that the specified annotation should also be written using the javadoc tool during use.

  @ TargetAnnotation is used to restrict the objects used by the annotation marked. This annotation 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 Declaration
  • ElementType.PARAMETERParameters that can be applied to a method
  • ElementType.TYPECan be applied to a class

  @ InheritedThe annotation type marked by the annotation prompt can be inherited from the superclass (not inherited by default). If the user does not retrieve the annotation of this type, the annotation will be retrieved from the parent class, this annotation can only be used in class declaration.

@ RepeatableAnnotations are introduced from Java 8. the type of the prompt mark can be used for the same element multiple times.

Type comment and pluggable Type System

Before Java 8, annotations can only be used in declarations. After Java 8, annotations can be used in any class, such as the creation expression (new) and conversion (cast) of the class instance ), implementation clause and throw clause (the usage of the preceding comments has been used as an example ).

Common types of annotations can be used to analyze java programming methods that support improved type checks. Java 8 SE does not provide a framework for type check, but you can compile or download a type check framework implemented by one or more modules used in combination with the java compiler, for example, the check Framework Checker Framework compiled by the University of Washington.

Search comments

Multiple methods in the Reflection API can be used to retrieve comments and return a single comment, such as AnnotatedElement. getAnnotationByType (Class <T>) does not change its behavior. After Java 8, a type annotation can be reused. For compatibility reasons, duplicate comments are stored in a comment container, which is automatically generated by the java compiler. Therefore, when there are repeated comments, you can obtain the comment containers with multiple comments first, in this way, the traditional method of returning a single comment can still be used. Java 8 also introduces a method that can return multiple comments at a time, such as AnnotatedElement. getAnnotations (Class <T> ).

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.