Deep understanding of Java: basic concepts of Annotation

Source: Internet
Author: User

What is annotation ):

Annotation (annotation) is a kind of metadata provided by Java.ProgramThe element in associates any information with any metadata (metadata.Annotion (annotation) is an interface. The program can obtain the annotion object of the specified program element through reflection, and then obtain the metadata in the annotation through the annotion object.

Annotation (annotation) is introduced in jdk5.0 and later versions. It can be used to create documents and trackCodeAnd even perform basic compile-time checks. In some ways, annotation is used like a modifier and applied to declarations of packages, classes, constructor, method, member variables, parameters, and local variables. The information is stored in the "name = value" structure of annotation.

Annotation MemberThe annotation type is declared in the form of a method without parameters. The method name and return value define the name and type of the member. There is a specific default Syntax: Allow declaring the default value of any annotation Member: An Annotation can use the name = value pair as the value of an annotation member without defining the default value, you can also use the name = value pair to overwrite the default values of other members. Some similar class inheritance features. The constructor of the parent class can be used as the default constructor of the subclass, but can also be overwritten by the quilt class.

Annotation can be used to associate any information for a program element (class, method, member variable, etc. Note that there isBasic rules: annotation does not affect the execution of program code. No matter how much annotation is added or deleted, the code is always executed.In addition, although some annotation is accessed at runtime through the Java reflection API method, the Java interpreter ignores these annotation at work. It is precisely because the Java Virtual Machine ignores annotation that the annotation type does not work in the Code. Only through a supporting tool can the annotation type information be accessed and processed. This article will cover the standard annotation and meta-annotation types. The tools that accompany these annotation types are Java compilers (of course, they must be processed in some special way ).

What is metadata ):

Metadata is translated from metadata, which means "data about data.
Metadata has many functions. For example, you may have used javadoc annotations to automatically generate documents. This is a type of metadata function. In general, metadata can be used to create documents, track code dependencies, and perform format check during compilation to replace existing configuration files. If you want to classify the role of metadata, there is no clear definition yet. However, we can divide it into three categories based on its role:
1. Compile the document: generate the document through the metadata identified in the code
2. Code Analysis: analyze the Code through the metadata identified in the code
3. Compilation check: the compiler can perform basic compilation check through the metadata identified in the code.
In Java, metadata is stored as tags in Java code. The existence of metadata tags does not affect compilation and execution of program code, it is only used to generate other files or the description of the Code to be run.
To sum up:
First, metadata is stored in Java code as tags.
Second, the metadata description information is type-safe, that is, the fields inside the metadata are clearly typed.
Third, metadata requires additional processing by tools outside the compiler to generate other program components.
Fourth, metadata can only exist in JavaSource codeLevel can also exist in the compiled class file.

 Annotation and annotation types:

Annotation:

Annotation uses the new syntax brought about by java5.0, and its behavior is very similar to modifiers such as public and final. Each annotation has a name and number of Members> = 0. Each annotation member has the name and value (like JavaBean) called the name = value pair, and name = value carries annotation information.

Annotation type:

The annotation type defines the annotation name, type, and member default value. An annotation type can be said to be a special Java interface. Its member variables are restricted, and the new syntax must be used to declare the annotation type. When we access annotation through the Java reflection API, the returned value will be an object that implements this annotation interface. By accessing this object, we can easily access its annotation member. The following sections will introduce three standard annotation types in the Java. lang Package of java5.0.

Annotation classification:

Based on the number of annotation parameters, we can divide the annotation into three types:
1. Tag annotation: an annotation type without Member definition is called Tag annotation. This annotation type only uses its own existence or not to provide us with information. For example, the system annotation @ override;
2. Single value Annotation
3. Complete Annotation

According to the annotation usage and usage, we can divide annotation into three types:
1. JDK built-in system Annotation
2. Metadata Annotation
3. Custom Annotation

 Built-in standard Annotations:

The annotation syntax is relatively simple. In addition to the use of the @ symbol, it is basically consistent with the inherent Java syntax. javase has three built-in standard annotations, which are defined in Java. LANG:
@ Override: modifies the method that overwrites the parent class;
@ Deprecated: used to modify outdated methods;
@ Suppresswarnnings: used to notify the Java compiler to disable specific compilation warnings.

Next, let's take a look at the functions and use cases of the three built-in standard annotations.

@ Override: Specifies the override parent class method.:

@ Override is a tag annotation type, which is used as the annotation method. It indicates that the labeled method overload the parent class method and plays the role of assertion. If we use this annotation, the Java compiler will warn you of a compilation error when a method that does not overwrite the parent class method. This annotaton is often used when we try to overwrite the parent class method and make sure that the method name is wrong. The method is extremely simple: when using this annotation, you only need to add @ override before the modified method. The following code uses @ override to modify a displayname () method that attempts to overload the parent class, and an example of spelling error exists:

 Public   Class  Fruit {  Public   Void  Displayname () {system. Out. println ( "Fruit name :*****" );}}  Class Orange Extends Fruit {@ override  Public   Void  Displayname () {system. Out. println ( "Fruit name: Orange" );}}  Class Apple Extends  Fruit {@ override  Public   Void  Displayname () {system. Out. println ( "Fruit name: Apple" );}} 
 
There will be no problems with the orange class compilation, and the Apple class will prompt corresponding errors during compilation. @ Override annotation can only be used for methods and cannot be used for other program elements.

@ Deprecated, mark as obsolete:

The same deprecated is also a tag annotation. When a type or type member is modified with @ deprecated, the compiler does not encourage the labeled program element. In addition, this modifier has a certain degree of "continuity": if we use this obsolete type or member in code through inheritance or overwrite, although the inherited or overwritten type or member is not declared as @ deprecated, the compiler still needs to issue an alert.

It is worth noting that the annotation type @ deprecated is different from the @ deprecated tag in javadoc: the former is recognized by the Java compiler, the latter is identified by the javadoc tool to generate documents (including descriptions of why a Program Member has passed, how it should be disabled or replaced ).

In java5.0, the Java compiler still looks for the javadoc tag @ deprecated as in the previous version and uses them to generate warning information. However, this situation will change in later versions. Now we should start to use @ deprecated to modify outdated methods instead of @ deprecated javadoc tag.

The following program uses the @ deprecated annotation to indicate that the method has expired. At the same time, the @ deprecated tag in the method annotation indicates that the method has expired. The Code is as follows:

  Class  Appleservice {  Public   Void  Displayname () {system. Out. println ( "Fruit name: Apple" );}  /**  *  @ Deprecated  This method has expired and is not recommended.  */  @ Deprecated  Public   Void  Showtaste () {system. Out. println ( "The taste of the fruit apple is sweet" );}  Public   Void Showtaste ( Int Typeid ){  If (Typeid = 1 ) {System. Out. println ( "The taste of the fruit apple is sour" );}  Else   If (Typeid = 2 ) {System. Out. println ( "The fruit's apple taste is sweet" );}  Else  {System. Out. println ( "The taste of the fruit apple is sweet" );}}}  Public   Class Fruitrun {  /**  *  @ Param  ARGs  */      Public   Static   Void  Main (string [] ARGs) {Apple = New  Apple (); apple. displayname (); appleservice = New Appleservice (); appleservice. showtaste (); appleservice. showtaste ( 0 ); Appleservice. showtaste ( 2 );}} 

The showtaste () method of the appleservice class is marked as an out-of-date method by @ deprecated. When used in the fruitrun class, the compiler will prompt that the method has expired and is not recommended.

Suppresswarnnings to suppress the compiler warning:

@ Suppresswarnings is used to warn the compiler to initialize classes, methods, member variables, and variables. In java5.0, The javac compiler provided by Sun provides the-xlint option for the compiler to warn against legal program code, which in turn represents a program error. For example, when we use a generic collection class without providing its type, the compiler will prompt a warning of "unchecked warning. Generally, when this happens, we need to find the code that generates the warning. If it really indicates an error, we need to correct it. For example, if the warning information indicates that the switch statement in our Code does not cover all possible cases, we should add a default case to avoid this warning.
Sometimes we cannot avoid this warning. For example, when we use a generic collection class that must interact with the old code of the non-generic, we cannot avoid this unchecked warning. At this time, @ suppresswarning will come in handy. Add @ suppresswarnings before calling the method to tell the compiler to stop warning about this method.
Suppresswarning is not a tag annotation. It has a member of the string [] type. The value of this Member is the forbidden warning name. For the javac compiler, the warning names that are valid by the-xlint option are also valid for @ suppresswarings, And the compiler ignores unrecognized warning names.
The annotation syntax allows annotation names followed by parentheses. The name = value pairs separated by commas are used to assign values to annotation members. Example:

 Public   Class  Fruitservice {@ suppresswarnings (Value = {"Rawtypes", "unchecked" }) Public   Static List <fruit> Getfruitlist () {list <Fruit> fruitlist = New  Arraylist ();  Return  Fruitlist;} @ suppresswarnings ({ "Rawtypes", "unchecked" })  Public   Static List <fruit> Getfruit () {list <Fruit> fruitlist = New Arraylist ();  Return  Fruitlist;} @ suppresswarnings ( "UNUSED" )  Public   Static   Void  Main (string [] ARGs) {list <String> strlist = New Arraylist <string> ();}} 

In this example, the suppresswarnings annotation type only defines a single member, so only one simple value = {...} is used as the name = value pair. Since the Member value is an array, braces are used to declare the array value. Note: We can abbreviated annotation in the following cases: when annotation only has a single member and the member name is "value = ". In this case, you can save "value = ". For example, the suppresswarnings annotation of getfruit () is abbreviated.

A brief description of common parameter values in the suppresswarnings annotation:

1. deprecation: warning when a class or method that is not in favor of use is used;
2. Unchecked: warning when unchecked conversion is executed. For example, when using a set, you do not use generic to specify the type of the set to be saved;
3. fallthrough: warning when the switch block directly leads to the following situation without break;
4. Path: warning when there are non-existent paths in the class path and source file path;
5. Serial: warning when serialversionuid definition is missing on serializable classes;
6. Finally: warning when any finally clause cannot be completed normally;
7. ALL: warning about all the above situations.

 

 

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.