Java Annotations (principles and their use)

Source: Internet
Author: User

I. Introduction of annotations (annotation)

Java introduces the annotation mechanism of source code in JDK5.

1. What is an annotation?

Annotations Add metadata to the code, which is descriptive information about the organization, data fields, and relationships of the data.

More generally, annotations add more visual descriptions to program elements that are not related to the business logic of the program and are intended for use by specific tools or frameworks.

Annotations can be embedded in a class file by the compiler, allowing the JVM to be retrieved at runtime, so annotations can be reflected;

Annotations can not directly affect the execution of code, or it can change the code execution process.

  

2. Target of annotations

Annotations are an interface through which the annotation information can be accessed by an API related to the reflection mechanism. The classes in a program framework or tool determine how to use program elements or change the behavior of the framework itself based on this information. However, annotations do not affect the actual execution of program code.

The purpose of the annotations is to have some information about the compiler or the relying framework (Spring) specifier, each of which corresponds to an actual annotation type.

3, the role of annotations in Java

    • Writing documents
    • Compile check
    • Project Build Instructions
    • Run-time Directives
    • Tracking Code Dependencies

4. Use of annotations

@ Note Name (configuration parameters)

When the annotation has more than one parameter, the parameter name must be declared, and the value of the annotation's configuration parameter must be a compile-time constant.

Annotations can be thought of as an XML element that can have different predefined properties, and the value of a property can be specified by itself when declaring the element. Using annotations in your code is equivalent to moving a subset of elements from an XML file into your code, managing and maintaining it in one place, and preserving the consistency of your code and metadata.

  

5. Create a custom annotation

Steps:

(1) Declare the annotation name by @interface, and then declare the member property (that is, the parameter) of the annotation in {}.

(2) Use the built-in meta-annotation labeling feature and limit the use of annotations.

PS: Automatically inherits java.lang.annotation.Annotation when customizing annotations

/* version Annotations */  public @Interface  version{    double number ();      // The annotation member type is double, named number.  }/*author Annotations * /public @Interface  author{     default "Unknown";     // The annotation member type is string and is named name. }

It is worth emphasizing that null cannot be the default value!

Use of annotations:

@Author (name= "Johny") @Version (number =1.0class  myconfig{         ...}

Two, Yuan annotations (meta-annotation)

Meta annotations are specifically designed to constrain other annotations, with four:

    • @Target
    • @Retention
    • @Documented
    • @Inherited

1. @Retention

Function: Defines the duration of the annotation being retained, that is, the life cycle of the annotation.

Configuration parameters: Retentionpolicy

public enum retentionpolicy{   SOURCE,   CLASS,   RUNTIME,    }

Some annotations appear only in the source code, are discarded by the compiler, and others are compiled in the class file, although they are read by the ClassLoader, but may be ignored by the JVM.

(the compiler leaves the annotation information in the. class file by default, providing information for the compiler or utility runtime)

If the programmer intends to design the Code analysis tool, it must have the JVM read out the annotation information so that it can be used when parsing the program. This is the time to set the meta-annotation @retention retentionpolicy as runtime, and then with the reflection mechanism, through the class class of the Getannotation () method to obtain the specified annotations, so that the information can be extracted at runtime annotations.

2. @Target

Function: Describes the scope of the object that the annotation modifies

Configuration parameters: ElementType (also enumerated type)

 Public enumElementType {/**Class, interface (including annotation type), or enum declaration*/TYPE,
/**Field declaration (includes enum constants)*/FIELD,/**Method Declaration*/METHOD,/**formal parameter declaration*/PARAMETER,/**Constructor Declaration*/CONSTRUCTOR,/**Local Variable Declaration*/local_variable,/**Annotation Type declaration*/Annotation_type,/**Package Declaration*/Package ,/*** Type Parameter declaration * *@since1.8*/Type_parameter,/*** Use of a type * *@since1.8*/Type_use}

/* Annotated version can be used only for cosmetic construction methods and methods */ @Target ({elementtype.constructor,elementtype.method}) @Retention (retentionpolicy.runtime) @Documented  public @Interface  version{    Double

3. @Documented

Function: Add the information of the annotations to the Help file, because no annotation information is added by default.

Configuration parameters: No.

When you use @documented to decorate annotation types, you must use @retention, and the configuration parameters retentionpolicy to runtime.

4. @Inherited

Function: Controls whether annotations affect subclasses, that is, if the annotation type is inherited, the successor remains in the subclass.

5. Read annotations at runtime

The parsing of annotations is entirely dependent on the reflection mechanism. After a program obtains a class object from a category by reflection, it is possible to invoke multiple methods of that object to obtain the annotation information for that class.

The reflection API provided by the Java.lang.reflect package expands the ability to read runtime annotation information, and it adds a Annotatedelement interface that represents program elements in the program that can accept annotations.

Application of annotations and reflection

1. Filtration Method

Annotations can modify a method to specify the nature or type of the method, allowing the caller of the method to filter the methods that can be invoked based on the annotation. In such applications, annotations act as markers to indicate whether the method meets the criteria.

2. Automated Test framework

Testing is an indispensable part of program design and a necessary means to improve the robustness of code.

However, code testing is often extremely complex to cover different code execution logic and paths, so the automated test framework can effectively improve the efficiency of code testing, which results in less effort.

The following example demonstrates how to implement a simple test framework with annotations to automate unit testing. This practice is applied extensively in the unit Test framework JUnit.

Iv. annotations of a single abstract method

The single abstract Method,sam annotation @functionalinterface has the function of restricting the interface and only one of the non-implemented methods, of course, there can be more than one implemented default method, obviously, It is for the lambda expression Service.

Java Annotations (principles and their use)

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.