Deep understanding of Java: basic concepts of Annotation and in-depth understanding of annotation

Source: Internet
Author: User

Deep understanding of Java: basic concepts of Annotation and in-depth understanding of annotation

What is Annotation ):

Annotation (Annotation) is a way and method for Java to associate any information with any metadata (metadata) in elements of a metaprogram. 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, track code dependencies, and 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.

The Annotation member is declared in the form of a non-parameter method in the Annotation type. 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. It should be noted that there is a basic rule here: Annotation cannot 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 at the Java source code level or within 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 method used to Override the parent class:

@ 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. It is not recommended to use */@ Deprecated public void showTaste () {System. out. println ("fruit apple taste: Sweet");} public void showTaste (int typeId) {if (typeId = 1) {System. out. println ("fruit apple taste: sour");} else if (typeId = 2) {System. out. println ("fruit apple taste: Sweet");} else {System. out. println ("fruit apple taste: Sweet") ;}} public class FruitRun {/*** @ param args */public static void main (String [] args) {Apple apple = new Apple (); apple. displayName (); AppleService 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.

Notes for learning Java !!!
If you have any questions or want to obtain learning resources during the learning process, join the Java learning exchange group: 159610322 let's learn Java together!

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.