Annotations to the Java core technology point

Source: Internet
Author: User
Tags deprecated modifier

Transferred from: http://www.open-open.com/lib/view/open1473649808122.html

What are annotations

We all know that the use of annotations in Java code is to explain something to someone who reads it later, that annotations are an upgraded version of comments that explain things to compilers, virtual machines, and so on. For example, we are very familiar with the @override is a meta-annotation, its role is to tell the compiler that its annotated method is to override the parent class method, so the compiler will check whether the parent class exists this method, and the method's signature is the same as the parent class.

In other words, annotations are used to describe Java code, which can be parsed by the compiler, and annotation processing tools can parse annotations at run time. We use annotations in the Java source file to better understand it when we or someone else reads the code later. The Javadoc tool can parse the descriptive information we add in the source code for classes, methods, variables, etc., and automatically generate an HTML document based on these descriptive information, as long as we add descriptive information for classes, methods, etc. to the syntax required by Javadoc. We are able to use the Javadoc tool to automatically generate a Help document based on our descriptive information. Annotations are much more powerful than Java annotations and Javadoc, and the big difference between them is that the role played by the Java annotations and Javadoc descriptions is only at compile time, and annotations are useful until run time.

We know that using the "transient" keyword can tell the compiler that the domain is not serializable. The annotations give us a more general way to add descriptive information to classes/methods/properties/variables than to use keywords like "transient", which are meaningful to developers, automation tools, Java compilers, and Java runtimes. This means that they can "read" the annotation information. The "transient" keyword is a modifier, and the annotation is also a modifier . In addition to passing information, we can also generate code using annotations. We can generate some "templated" code by using annotations and then having the annotation parsing tool parse them. For example, Hibernate, Spring, and axis These frameworks use annotations extensively to avoid duplication of effort.

Meta Annotations

Meta-annotations are used to describe annotations, such as the following code, where we use the "@Target" meta-annotation to illustrate that the methodinfo annotation can only be used to annotate a method:

@Target (elementtype.method) public @interface MethodInfo {   ...}

Let's give a detailed introduction to several meta-annotations.

documented

When an annotation type is described by the @documented meta-annotation, it is documented by the Javadoc tool wherever the annotation is used. Let's take a look at its definition:

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type) public @interface documented {}

As we can see from the code above, defining annotations uses the @interface keyword , which is just like using the class keyword when defining a class, and using the interface keyword when defining an interface, annotations are also a type. This meta-annotation is @documented decorated to indicate that it is also documented. The value of the @Retention meta annotation retentionpolicy.runtime represents @documented this annotation can be persisted to the runtime; the value of the @Target meta annotation Elementtype.annotation_ Type denotes @documented This annotation can only be used to describe the annotation type.

inherited

Indicates that the modified annotation type is automatically inherited. The specific explanation is as follows: If an annotation type is modified by the inherited meta-annotation, when the user queries the annotation type in a class declaration, if it is found that the annotation type is not included in the class declaration, the corresponding annotation type is automatically queried in the parent class of the class, and the process is repeated. The object class was not found until the annotation type was found or was completed. This meta-annotation is defined as follows:

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type) Public @interface inherited {}

We can see that this meta-annotation type is annotated by @documented and can be persisted to the runtime and can only be used to describe the annotation type.

Retention

We've already seen this meta-annotation above, which indicates when an annotation type will be retained, such as the following code, which indicates that the developer annotation is persisted to the runtime:

@Retention (retentionpolicy.runtime) public @interface Developer {   String value ();}

The @Retention meta annotations are defined as follows:

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type) public @interface Retention {     retentionpolicy value ();}

When we use @retention, the contents of the parentheses indicate his value, from the above definition we can see that the type of the value is Retentionpolicy, which is an enumeration type, which can take the following values:

    • SOURCE: Indicates that this annotation will be removed at compile time and will not be included in the class file generated after compilation;

    • Class: Indicates that the annotation will be included in the class file, but will be removed at run time;

    • Runtime: This annotation is persisted to runtime and can be accessed by the JVM at run time, and we can parse the annotation at runtime by reflection.

Target

This meta-annotation illustrates the scope of application of the modified annotations, that is, the modified annotations can be used to annotate which program elements, which are defined as follows:

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type) public @interface Target {     Elementtype[] Value ();}

From the above definition we can see that it is also persisted to the runtime, and its value is elementtype[] Type (an array, meaning that multiple values can be specified), ElementType is an enumeration type, which can take the following values:

    • Type: Represents a class, interface, annotation type, or enumeration type that can be used for annotations;

    • Package: can be used to annotate packages;

    • PARAMETER: Can be used to annotate parameters;

    • Annotation_type: Can be used to annotate annotation types;

    • Method: Can be used to annotate methods;

    • FIELD: Can be used to annotate attributes (including enumeration constants);

    • CONSTRUCTOR: Can be used to annotate the constructor;

    • Local_variable: Can be used to annotate local variables.

Common built-in annotations

There are some annotations in Java itself, so let's look at some of the more common annotations we have in our daily development: @Override, @Deprecated, @SuppressWarnings. I believe we have all used these three annotations more or less, and let's look at them again.

@Override Annotations

Let's look at the definition of this annotation type first:

@Target (Elementtype.method) @Retention (retentionpolicy.source) public @interface Override {}

From its definition we can see that this annotation can be used to modify the method, and it is only valid at compile time, no longer exists in the compiled class file. The effect of this annotation is not unfamiliar to us, that is to tell the compiler is decorated by the method is overridden in the parent class of the same signature method, the compiler will check this, if it is found that the parent class does not exist in this method or the existence of the method signature is different, it will be an error.

@Deprecated

The definition of this annotation is as follows:

@Documented @retention (retentionpolicy.runtime) @Target (Value={constructor, FIELD, local_variable, METHOD, package, PARAMETER, TYPE}) public @interface Deprecated {}

From its definition we can know that it will be documented and able to be persisted to the runtime, able to modify construction methods, properties, local variables, methods, packages, parameters, types. The purpose of this annotation is to tell the compiler that the program element being decorated is "deprecated" and is no longer recommended for use by users.

@SuppressWarnings

This annotation we also more commonly used, first of all to see its definition:

@Target ({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, local_variable}) @Retention (Retentionpolicy.source) public @ Interface Suppresswarnings {     string[] value ();}

It can modify the program elements including types, properties, methods, parameters, constructors, local variables, only live in the source code, the value is string[]. Its purpose is to tell the compiler to ignore the specified warning message, and it can take the following values:

    • Deprecation: Ignores warnings when deprecated classes or methods are used;

    • Unchecked: A non-checked conversion was performed;

    • The case is left in the Fallthrough:swich statement block to "fall into" the next case directly;

    • Path: Class path or original file path, etc. does not exist;

    • Serial: The serializable class lacks serialversionuid;

    • Finally: there is a finally clause that cannot be executed properly;

    • All: Warnings generated by all of the above are ignored.

Examples of use of this annotation are as follows:

@SuppressWarning (value={"deprecation", "unchecked"}) public void Mymethos () {  ...}

By using the above annotations, we tell the compiler to ignore warnings that result from the use of deprecated classes or methods in the MyMethod method, or from unchecked conversions.

Custom Annotations

We can create our own annotation types and use it. Take a look at the following example:

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.method) @Inheritedpublic @interface MethodInfo {     String author () default "Absfree";     String date ();     int version () default 1;}

When customizing annotations, here are a few things we need to know:

    • The annotation type is defined by the "@interface" keyword;

    • In the annotation body, all methods do not have a method body and allow only public and abstract modifier symbols (no modifier defaults to public), and the annotation method does not allow the throws clause;

    • The return value of the annotation method can only be as follows: Raw data type), String, Class, enum type, annotations, and one-dimensional arrays of them, you can specify a default return value for the method.

Let's take a look at the definition of the annotation type mentioned above @suppresswarnings, this annotation type is defined by the system for us, and it is defined as follows:

@Target ({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, local_variable}) @Retention (Retentionpolicy.source) public @ Interface Suppresswarnings {     string[] value ();}

As we can see, it defines only one annotation method, value (), whose return value type is string[], and does not specify a default return value. The syntax we use to @suppresswarnings this annotation is as follows:

@SuppressWarnings (value={"value1", "value2", ...})

That is, you can use this annotation by specifying a return value for each annotation method in parentheses after the name of the annotation type. Let's take a look at how to use our custom annotation type @methodinfo:

public class Annotationtest {     @MethodInfo (author= "Absfree", date= "20160410") public          static void Main (string[] args) {         System.out.println ("Using custom Annotation ...");}     }

So now the question is, do we use custom annotations that are meaningful to the compiler or virtual machine (compiler or virtual function readable)? Obviously we don't do anything, the compiler or the virtual machine is not reading our custom annotations. Let's describe the parsing of the following annotations so that the compiler or virtual machine can read our custom annotations.

Parsing of annotations compile-time parsing

Compile-time annotations refer to annotations with the value of class @retention, and for parsing of such annotations, we only need to do the following two things:

    • The custom class inherits the Abstractprocessor class;

    • Override the process function within it.

The compiler then automatically finds all classes that inherit from Abstractprocessor at compile time, and then calls their process method. So as long as we do the above two things, the compiler will take the initiative to parse our compile-time annotations. Now that we have changed the retention of the MethodInfo defined above to CLASS, we can parse it according to the following code:

@SupportedAnnotationTypes ({"Com.custom.customannotation.MethodInfo"}) public class Methodinfoprocessor extends abstractprocessor {   @Override public   boolean process (set<? extends typeelement> annotations, Roundenvironment env) {     hashmap<string, string> map = new hashmap<string, string> ();     for (Typeelement typeelement:annotations) {for       (Element element:env.getElementsAnnotatedWith (typeelement)) {
   methodinfo MethodInfo = element.getannotation (methodinfo.class);         Map.put (Element.getenclosingelement (). toString (), Methodinfo.author ());       }     }     return false;   }}

@SupportedAnnotationTypes annotations Describe the names of the annotations processor to parse. The annotations parameter of the process function represents the set of annotations to be processed, and Env represents the current or previous operating environment. The return value of the process function indicates whether the annotations in annotations are accepted by this processor.

For more detailed information please refer to Android using APT technology to generate code at compile time

run-time annotation parsing

First we change the value of retention in the MethodInfo annotation type back to the original runtime, and then we show how to parse our custom annotation types at run time through the reflection mechanism.

There is a annotatedelement interface in the Java.lang.reflect package that defines several methods for obtaining annotation information:

Returns an annotation of the specified type of the program element, and returns Nullt getannotation (Class annotationclass)//Returns all annotations that decorate the program element if no annotation of that type exists annotation[] Getannotations ()//returns all annotations that directly decorate the element annotation[] getdeclaredannotations ()//returns TRUE if the program element is a specified type annotation adornment, otherwise returns Falseboolean Isannotationpresent (class<? extends annotation> Annotationclass)

The example code that parses our custom annotation MethodInfo above is as follows (Annotationparser.java):

public static void Main (string[] args) {     try {         Class cls = annotationtest.class;         For (Method method:cls.getMethods ()) {         MethodInfo MethodInfo = method.getannotation (methodinfo.class);         if (methodInfo! = null) {         System.out.println ("Method Name:" + method.getname ());         System.out.println ("method Author:" + Methodinfo.author ());         System.out.println ("Method Date:" + methodinfo.date ());         System.out.println ("method version:" + methodinfo.version ());}}}     catch (Exception e) {     e.printstacktrace ();     }}

Running the above code we can get the following output:

This shows that we have successfully parsed the custom annotations. About annotations We need to be clear that, as a meta-data describing the code itself, annotations are a "passive" message. That is, it must be "actively" parsed by the compiler or virtual machine to play its part.

References
    1. Java documention
    2. Java annotations for the public technology point
    3. Java annotations

From: Http://www.jianshu.com/p/8673bc2d5dec

Annotations to the Java core technology point

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.