Java uses the annotation processor to generate code-Part 1: annotation type

Source: Internet
Author: User

Java uses the annotation processor to generate code-Part 1: annotation type

Starting from this article, I will begin to write a series of articles about using the annotation processor to generate code in Java, including the power of this method. It also describes how to ensure that the source code is generated using this method during compilation.

In this series of articles, we will:

This section describes Java annotations. Measure the test taker's understanding about the common methods and scope of use of annotations. Understand annotation processors and their roles. Learn how to create annotation processors. Learn how to run the annotation processor in terminal command line, Eclipse, and Maven. Learn how to use the annotation processor to generate source code. Learn how to use an external template engine like Apache Velocity to generate source code using annotation processors. Collation

Java annotations are introduced from the Java language specification (1) of the third edition and supported in Java 5.

Through annotation, we can add metadata information for source code, including compilation or deployment information, configuration attributes, compilation behavior, or code quality check.

Different from Javadoc, annotations are strongly typed and can be used to find the corresponding annotation type definition under the class path. Therefore, defined annotations can be accessed at runtime, while Javadoc is impossible.

Annotation syntax

Annotations usually appear in front of the annotated code segment, which is usually independent and indented as the code segment.

Annotations can be added to package and types (types, including classes, interfaces, enumerations, and other annotation types), variable (variables, including class, class instances, local variables-including local variables defined in the for or while LOOP), constructions (constructor), methods (method) and parameters ).

The simplest annotation structure is that there are no internal elements, for example:

@Override()public void theMethod() {…}

In this example, parentheses can be omitted (because there is no parameter ):

@Overridepublic void theMethod() {…}

Annotations can also contain elements, which are key-value pairs separated by commas. The allowed value types include the java Native data type, String type, enumeration type, and the array form of these types:

@Author(name = Albert,        created = 17/09/2010,        revision = 3,        reviewers = {George, Fred})public class SimpleAnnotationsTest {…}

When there is only one element in the annotation and the element is named value, the element name can be omitted:

@WorkProduct(WP00000182)@Complexity(ComplexityLevel.VERY_SIMPLE)public class SimpleAnnotationsTest {…}

Annotations can be used to set default values for some or all internal elements. Elements with default values can be omitted when such annotations are used.

For example, assume that an annotation is Author, which sets the default value for the internal element revision (1 by default) and reviewers (empty String array by default, the following two annotations are equivalent:

@Author(name = Albert,        created = 17/09/2010,        revision = 1,        reviewers = {})public class SimpleAnnotationsTest() {…}@Author(name = Albert,        // defaults are revision 1        created = 17/09/2010) // and no reviewerspublic class SimpleAnnotationsTest() {…}
Typical use of annotations

Three annotation types are defined in the Java language specification-they are all used in the Java compiler:

@ Deprecated:The element used to declare the annotation should not be used again. The compiler generates a warning whenever this annotation is used. It should be used with @ deprecated of Javadoc to explain the reason why the annotation element is discarded in Javadoc.

@ Override:The element used to declare the annotation overwrites the element declared in the parent class. If the element to be annotated does not find the corresponding overwritten element in the parent class, the compiler generates a warning. Although this annotation is not required to be used, it is very useful for error judgment-for example, if someone modifies the signature of the parent class method after the parent class is created, so we will be immediately reminded when re-compiling the source code.

@ SuppressWarnings:Let the compiler suppress the specified Warning type, otherwise the annotated elements will trigger such warnings-for example, in order to avoid excessive compiler "interference" by using discarded APIs or interacting with old Code (for example, a version earlier than Java 5 ".

Since these annotations are introduced, many libraries and frameworks have integrated annotations into their new release versions. By using annotations in the source code, these libraries and frameworks simplify or even remove the required configuration files.

The following are examples of successfully using Annotations:

Java Enterprise Edition and its main modules-enterprise-level JavaBeans, Java persistence APIs, or Web Service APIs. Spring framework-used for configuration, dependency annotation, control inversion in core modules, and other Spring projects. Sean, Weld, Guice. Apache Struts 2. Annotation type

In Java, the annotation type is a special interface that uses a custom annotation.

Annotation definition needs to be used@ InterfaceKeyword to replaceInterface:

public @interface Author {    String name();    String created();    int revision() default 1;    String[] reviewers() default {};}public @interface Complexity {    ComplexityLevel value() default ComplexityLevel.MEDIUM;}public enum ComplexityLevel {    VERY_SIMPLE, SIMPLE, MEDIUM, COMPLEX, VERY_COMPLEX;}

There are some differences between annotation types and common interfaces:

Only native data types, String, enumeration, class, and arrays of these types are allowed. Note that common objects and arrays are not allowed in the annotation type (because each array is an object ).

The definition of annotation elements is similar to the syntax for defining methods, but modifiers and parameters are not allowed.

The default value of the annotation element must be definedDefaultKeyword, followed by the link literal, initialization array, or enumeration value.

Like other classes or interfaces, enumeration types can also be nested inside the annotation type:

public @interface Complexity {    public enum Level {        VERY_SIMPLE, SIMPLE, MEDIUM, COMPLEX, VERY_COMPLEX;    }    …}
Annotation used to define Annotation

JDK comes with some annotations used to modify the default behavior of custom annotations.

@ Brief ented:Declare the annotation type after @ brief ented annotation. Once used, the annotated elements should be recorded in Javadoc together with the annotation.

@ Inherited:Declare that the annotation type to be annotated can inherit from its subclass. In this way, if the current subclass has not been annotated with the annotation type annotation of @ Inherited, but its parent class has, the current subclass can also inherit this annotation type. However, it only applies to class inheritance and does not apply to interface implementation.

@ Retention:Declare the life cycle of the annotation type to be annotated. Optional values are included in the RetentionPolicy enumeration:CLASS(Default value: can be included in the class file, but cannot be accessed at runtime ),SOURCE(The class file will be discarded by the compiler when it is created ),RUNTIME(Can be accessed during running ).

@ Target:Declares the element types that can be annotated by the annotation type. Optional values are included in the ElementType enumeration:ANNOTATION_TYPE(For annotation type ),CONSTRUCTOR(Used for Constructor ),FIELE(Used for member variables ),LOCAL_VARIABLE(For local variables ),METHOD(Used for methods ),PACKAGE(For packages ),PARAMETER(Used for method parameters ),TYPE(Used for classes, interfaces, and enumeration ).

 

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.