Deep analysis of Java annotations

Source: Internet
Author: User
Tags deprecated

Note, I believe everyone will know, like @requestmapping, @Resource, @Controller and so on some of the annotations, we have used, then, his tool class you used it? Let's share the annotation tool class with you.

The role of annotations:

1. Generate the document. This is the most common, and also the earliest annotations that Java provides. Commonly used @see @param @return, etc.

2, tracking code dependencies, to implement the alternative configuration file function. The most common is the annotation-based configuration that starts with spring 2.5. The function is to reduce the configuration. Now the framework basically uses this configuration to reduce the number of configuration files. After the Java program development, the most will also implement annotation configuration, with great use;

3, at compile time to check the format. such as @override before the method, if you do not override the method of the superclass method, compile time can be checked out.

Classification of annotations:

Based on the usage and use of annotations, we can divide annotation into three categories:
1.JDK built-in system annotations
2. Meta-annotations
3. Custom annotations

system built-in standard annotations:

The syntax of annotations is relatively simple, except for the use of the @ symbol, which is basically consistent with Java's inherent syntax, with three standard annotations built into Java, defined in Java.lang:
@Override: A method used to decorate this method that overrides the parent class;
@Deprecated: Used to modify a method that is obsolete;
@SuppressWarnnings: Used to notify the Java compiler against specific compilation warnings.

Let's look at the roles and usage scenarios of the three built-in standard annotations in turn.

@Override , to qualify the Override parent class method :

@Override is a markup annotation type that is used as a labeling method. It illustrates the way that the annotated method overloads the parent class and plays the role of the assertion. If we use this annotation in a method that does not overwrite the parent class method, the Java compiler will alert you with a compilation error. This annotaton often works when we try to override the parent method and write the wrong method name. The method of use is extremely simple: when using this annotation, just precede the modified method with @override. @Override annotations can only be used for methods and not for other program elements.

@Deprecated , the token is obsolete:

The same deprecated is also a marker annotation. When a type or type member uses the @deprecated modifier, the compiler will not encourage the use of this annotated program element. And this modification has a certain "continuity": If we use this obsolete type or member in the code by inheriting or overwriting it, although the inherited or overwritten type or member is not declared as @Deprecated, But the compiler still has to call the police.

It is worth noting that this tag is different @Deprecated this annotation type and the @deprecated in Javadoc: The former is recognized by the Java compiler, The latter is a description that is used by the Javadoc tool to generate documents that contain why a program member is obsolete, how it should be banned or substituted.

The Java5.0,java compiler still looks for @deprecated this Javadoc tag as it did in previous versions, and uses them to generate warning messages. But this situation will change in subsequent versions, and we should now start using @deprecated to decorate obsolete methods instead of @deprecated Javadoctag.

@SuppressWarnnings , suppress compiler warnings:

@SuppressWarnings is used to have a selective shutdown compiler warning for classes, methods, member variables, and variable initialization. The Javac compiler provided by Java5.0,sun gives us the-xlint option to warn the compiler of legitimate program code, which in some way represents a program error. For example, when we use a generic collection class without providing its type, the compiler will prompt for a "uncheckedwarning" warning. Usually when this happens, we need to find the code that caused the warning. If it does indicate an error, we need to correct it. For example, if the warning message indicates that the switch statement in our code does not overwrite all possible case, then we should add a default instance to avoid this warning.
Sometimes we cannot avoid this warning, for example, we cannot avoid this unchecked warning when we use generic collection classes that must interact with non-generic old code. At this point the @suppresswarning will come in handy, add the @suppresswarnings modifier before the calling method, and tell the compiler to stop warning about this method.
  @SuppressWarning is not a tag annotation. It has a member of type string[] , and the value of this member is the forbidden warning name. For the javac compiler, a warning name that is valid by the-xlint option is also valid for @SuppressWarings . At the same time, the compiler ignores unrecognized warning names.

Simple description of common parameter values for suppresswarnings annotations:

1.deprecation: Warning when using a class or method that is not in favor of use;
2. Unchecked: Warnings when an unchecked conversion was performed, such as when using a collection without generics (generics) to specify the type of collection to save;
3. Fallthrough: When the switch block directly leads to the next situation without a break warning;
4. Path: Warning when there are no paths in the classpath, source file path, etc.
5. Serial: A warning when a SERIALVERSIONUID definition is missing on a serializable class;
6. Finally: a warning when any finally clause does not complete properly;
7. All: Warnings about all of the above.

The following is a simple application of the JDK's built-in system annotations:

Meta-Annotations:

The role of meta annotations is to be responsible for annotating other annotations. Java5.0 defines 4 standard meta-annotation types, which are used to provide descriptions of other annotation types. Java5.0 defined meta-annotations:
[Email protected],
[Email protected],
[Email protected],
[Email protected]
These types and the classes they support can be found in the Java.lang.annotation package. Let's take a look at the function of each meta-annotation and the instructions for using the corresponding sub-parameters.

 @Target :

@Target illustrates the range of objects that annotation modifies: annotation can be used for packages, types (classes, interfaces, enumerations, annotation types), type members (methods, constructor methods, member variables, enumeration values), Method parameters and local variables (such as loop variables, catch parameters). Target can be more clearly decorated by using target in the declaration of the annotation type.

Function: Used to describe the scope of use of annotations (i.e., where the annotations described can be used)

 Take value (ElementType) are:

1.CONSTRUCTOR: Used to describe the constructor
2.FIELD: Used to describe the domain
3.local_variable: Used to describe local variables
4.METHOD: Used to describe the method
5.PACKAGE: Used to describe the package
6.PARAMETER: Used to describe parameters
7.TYPE: Used to describe classes, interfaces (including annotation types) or enum declarations

@Retention :

  @Retention defines how long the annotation is retained: Some annotation appear only in the source code and are discarded by the compiler, while others are compiled in the class file The annotation that are compiled in the class file may be ignored by the virtual machine, while others will be read when class is loaded (note that it does not affect class execution because annotation is separated from the class in use). Using this meta-annotation can limit the "life cycle" of annotation.

  Function: Indicates the level at which the annotation information needs to be saved to describe the life cycle of the annotation (i.e., the scope of the annotation being described is valid)

 Value ( Retentionpoicy ) are:

1.SOURCE: Valid in source file (i.e., source file retention)
2.CLASS: Valid in class file (that is, class reserved)
3.RUNTIME: Valid at run time (that is, runtime retention)

The retentionmeta-annotation type has a unique value as a member, and its value is derived from the Java.lang.annotation.RetentionPolicy enumeration type value.The retentionpolicy attribute value of Column annotations is rutime so that the annotation processor can be reflected, Gets the attribute value of the annotation to do some logical processing of the runtime                                                                                                                                                                                                                                                                                                                                                                                                                                                                         

@Documented:

  @ Documented is used to describe other annotation types that should be considered as public APIs for annotated program members, so they can be documented by tools such as Javadoc. Documented is a markup annotation with no members.

@Inherited :

  @Inherited meta-annotation is a markup annotation, @Inherited illustrates that a type that is labeled is inherited. If one uses the @Inherited Decoration of annotation type is used for a class , then this annotation will be used for the class sub-class.

Note: @Inherited the annotation type is inherited by subclasses of the class that is labeled. The annotation class does not inherit from the interface it implements, and the method does not inherit annotation from the method it overloads.

The reflection API enhances this inheritance when the retention of the @inherited annotation type callout annotation is retentionpolicy.runtime. If we use Java.lang.reflect to query the annotation of a @inherited annotation type, the reflection code check will work: Examine the class and its parent class until the specified annotation type is found, or reach the top level of the class inheritance structure.

Custom annotations:

When you use @interface custom annotations, the Java.lang.annotation.Annotation interface is automatically inherited and other details are automatically completed by the compiler. When you define annotations, you cannot inherit other annotations or interfaces. @interface is used to declare an annotation, in which each method actually declares a configuration parameter. The name of the method is the name of the parameter, and the return value type is the type of the parameter (the return value type can only be base type,Class,String,enum). You can declare the default value of a parameter through default.

  To define the annotation format:
  Public @interface annotation name {definition body }

  Supported data types for annotation parameters:

1. All basic data types (int,float,boolean,byte,double,char,long,short)
2. String type
3. Class type
4. Enum type
5. Annotation type
6. Arrays of all types above

  How to set the parameters of the annotation type:
First , it can only be decorated with public or default access rights. For example,String value (), where the method is set to defaul default type;
Second , parameter members can only use basic types Byte,short,char,int,long,float,double,boolean eight basic data types and String, Enum, Class, Data types such as annotations, and arrays of these types. For example, string value (), where the parameter member is string;
Third , if there is only one parameter member, it is best to set the parameter name to "value", followed by parentheses. For example, the following example fruitname annotation has only one parameter member.

The following is an implementation of a reflection mechanism to get the annotation value, so that you can learn more about annotations and understand the reflection mechanism in Java.

The first is the custom annotations Helloannotation2.java

Package Test;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target; @Retention (retentionpolicy.runtime) @ Target ({elementtype.type,elementtype.method,elementtype.parameter}) public @interface HelloAnnotation2 {String Color () Default "red"; String age ();}

Helloannotation3.java

Package Test;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target; @Retention (retentionpolicy.runtime) @ Target ({Elementtype.type,elementtype.field}) public @interface HelloAnnotation3 {String getaddress (); String Tel () default "110";}

Test class Annotationtest.java

Package Test;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import java.lang.reflect.method;/** * Function: Test annotation * Time: December 12, 2016 9:07:28 * Juzih */public class Annotationtest {@HelloAn Notation2 (age= "2") public static string Testcolor (string color) {System.out.println (color); return color;} @HelloAnnotation3 (getaddress= "Haidian District, Beijing") String address;public static void Main (string[] args) {//Gets the annotation value on the method method[] Methods = AnnotationTest.class.getDeclaredMethods (); if (methods! = null) {for (Method method:methods) {HelloAnnotation2 Anntotion2 = Method.getannotation (Helloannotation2.class); if (anntotion2 = = null) {continue;} Method[] me = Anntotion2.annotationtype (). Getdeclaredmethods (); for (Method Meth:me) {try {String color = (string) meth.i Nvoke (anntotion2, NULL); System.out.println ("Gets the annotation value on the method:" +color);} catch (Illegalaccessexception e) {e.printstacktrace ();} catch (IllegalArgumentException e) {e.printstacktrace ();} catch (InvocationTargetException e) {E.printstaCktrace ();}}} Gets the annotation value on the field annotationtest noon = new Annotationtest (); field[] field = AnnotationTest.class.getDeclaredFields (); if (field! = null) {for (field Fie:field) {if (!fie.isaccessible ()) {fie.setaccessible (true);} HelloAnnotation3 Annon = fie.getannotation (Helloannotation3.class); method[] meth = Annon.annotationtype (). Getdeclaredmethods (); for (Method Me:meth) {if (!me.isaccessible ()) { Me.setaccessible (TRUE);} try {Fie.set (noon, Me.invoke (Annon, null)); System.out.println ("Gets the annotation value on the field:" +fie.get (noon));} catch (IllegalArgumentException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch ( Illegalaccessexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (InvocationTargetException e) { TODO auto-generated catch Blocke.printstacktrace ();}}}}}

Operation Result:

Gets the annotation value on the method: Red gets the annotation value on the method: 2 Gets the annotation value on the field: Haidian District, Beijing gets the annotation value on the field: 110

  

Deep analysis of Java 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.