[1] Annotations (Annotation)--in-depth understanding of Java: Annotations (Annotation) Basic concepts

Source: Internet
Author: User
Tags deprecated

Reprint http://www.cnblogs.com/peida/archive/2013/04/23/3036035.html

In-depth understanding of Java: Annotations (Annotation) Basic concepts

What is an annotation (Annotation):

  Annotation (note) Is that Java provides a way and a way for an element in a meta-program to correlate any information with any metadata (metadata). annotion (annotation) is an interface that a program can use to get the Annotion object of a specified program element, and then obtain the metadata within the annotation by Annotion object.

Annotation (note) was introduced in JDK5.0 and later versions. It can be used to create documents, track dependencies in code, and even perform basic compile-time checks. In some ways, annotation is used like a modifier and is applied to the declaration of a package, a type, a constructor method, a method, a member variable, a parameter, a local variable. This information is stored in the annotation "name=value" structure pair.

  the members of the annotation are declared in the annotation type in the form of a parameterless method. Its method name and return value define the name and type of the member. Here is a specific default syntax: Allows you to declare the default value for any annotation member: A annotation can use Name=value as a value for a annotation member that does not have a default value defined, and of course it can be used name= The value pair overrides the other member's default value. This is somewhat similar to the inheritance attribute of the class, where the constructor of the parent class can be the default constructor for the subclass, but it can also be overridden by the quilt class.

Annotation can be used to associate any information with a program element (class, method, member variable, and so on). It is important to note that there is a basic rule here: Annotation does not affect the execution of program code, regardless of the addition or deletion of Annotation, the code is consistently executed. In addition, while some annotation are accessed at run time through the Java Reflection API approach, the Java language interpreter ignores these annotation when it works. It is the Java virtual machine that ignores the annotation, which causes the annotation type to "not work" in the code, and the information in the annotation type is accessed and processed only by a matching tool. This article will cover the standard annotation and meta-annotation types, and the tools that accompany these annotation types are the Java compilers (and of course they are handled in a special way).

What is metadata (meta data):

Metadata is translated from the word metadata, which means "data about data".
There are many functions of meta data, such as: You may have used Javadoc annotations to automatically generate documents. This is one of the meta-data functions. In general, metadata can be used to create documents, keep track of code dependencies, and perform compile-time format checks instead of existing configuration files. If you want to classify the role of metadata, there is no clear definition, but we can according to its role, broadly can be divided into three categories:
1. Writing a document: Generating a document from the metadata identified in the code
2. Code Analysis: Analyze code with metadata identified in code
3. Compile check: The compiler can implement the basic compilation check through the metadata identified in the code
In Java, metadata exists in Java code in the form of tags, and the presence of metadata tags does not affect the compilation and execution of program code, but is used to generate other files or needles that know the description of the running code at run time.
Sum up:
First, the metadata exists in the Java code in the form of a label.
Second, metadata describes the information that is type-safe, that is, the fields within the metadata are explicit types.
Third, metadata requires additional processing by tools outside the compiler to generate additional program parts.
The metadata can exist only at the Java source level, or it can exist inside a compiled class file.

Annotation and annotation types:

  Annotation:

annotation uses the new syntax introduced in java5.0, which behaves much like a modifier such as public and final. Each annotation has a name and a number of members >=0. Each member of the annotation has a name and value (like JavaBean) called the Name=value pair, and name=value loads the annotation information.

  Annotation type:

  The annotation type defines the annotation name, type, and member default values. A annotation type can be said to be a special Java interface whose member variables are restricted, and the new syntax is required when declaring annotation types. When we access annotation through the Java Reflection API, the return value will be an object that implements the annotation type interface, which we can easily access to its annotation members by accessing this object. The following chapters will refer to the 3 standard annotation types contained in the Java.lang package of java5.0.

Classification of annotations:

Depending on the number of annotation parameters, we can divide the annotations into three categories:
1. Tag annotations: A annotation type that has no member definition is called a tag annotation. This type of annotation only uses its own presence or not to provide information to us. For example, the following system annotation @override;
2. Single value annotations
3. Full 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 the native syntax of Java, with three standard annotations built into the javase, 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, restrict overriding the 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 then write the wrong method name. The method of use is extremely simple: when using this annotation, just precede the modified method with @override. The following code is an instance of the DisplayName () method that uses @override to modify an attempt to reload the parent class, with a misspelling:

PublicClass Fruit {public void< Span style= "color: #000000;" > DisplayName () {System.out.println ("The name of the fruit is: * * * * * * * * *" class Orange extendspublic void  DisplayName () {System.out.println ("The name of the fruit is: orange" extendspublic void  DisplayName () {System.out.println ("The name of the fruit is: Apple"   
The Orange class compiles without any problems, and the Apple class prompts for the appropriate error when compiling. @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, 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 Javadoc tag.

The following procedure uses the @deprecated annotation notation method to expire, and in the method note with @deprecated tag that the method is obsolete, the code is as follows:

 ClassAppleservice {PublicvoidDisplayName () {System.out.println ("The name of the fruit is: Apple"); }/***@deprecatedThis method has expired and is not recommended for use*/@DeprecatedPublicvoidShowtaste () {System.out.println ("The apple of the fruit tastes: crisp and sweet"); }Publicvoid Showtaste (IntTYPEID) {if (typeid==1{System.out.println ("Fruit of the Apple's taste: sour"); }Elseif (typeid==2{System.out.println ("The fruit of the apple taste is: Cotton sweet"); }Else{System.out.println ("Fruit of the Apple's taste is: crisp sweet"); }}}public class/**  @param Span style= "color: #008000;" > args */public static Span style= "color: #0000ff;" >void Main (string[] args) {Apple apple=new Apple (); Apple.displayname (); Appleservice appleservice=new Appleservice (); Appleservice.showtaste (); Appleservice.showtaste (0 ); }} 

The Showtaste () method of the Appleservice class is labeled as obsolete by @deprecated, and when used in the Fruitrun class, the compiler gives hints that the method has expired and is not recommended for use.

Suppresswarnnings, suppressing 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 the warning "unchecked 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 markup annotation. It has a member of type string[], and the value of this member is the forbidden warning name. For the Javac compiler, the warning name that is valid by the-xlint option is also valid for @suppresswarings, and the compiler ignores the unrecognized warning name.
The annotation syntax allows the annotation name to be followed by parentheses, where the comma-separated name=value is used to assign values to the members of the annotation. Examples are as follows:

PublicClassFruitservice {@SuppressWarnings (value={"Rawtypes", "unchecked"})PublicStatic list<fruit>Getfruitlist () {list<fruit> fruitlist=New ArrayList (); return fruitlist;} @SuppressWarnings ({"Rawtypes", " Unchecked "public  Getfruit () {list<fruit> fruitlist=new ArrayList (); return fruitlist;} @SuppressWarnings ("Unused" ) public static void< Span style= "color: #000000;" > main (string[] args) {list<string> strlist=new Arraylist<string>(); }} 

In this example suppresswarnings annotation type only defines a single member, so there is only one simple value={...} As a name=value pair. And because the member value is an array, use curly braces to declare the value of the array. Note: We can abbreviate annotation in the following scenario: When annotation has only a single member and the member is named "Value=". This can save "value=". For example, the above method Getfruit () suppresswarnings annotation is abbreviated.

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: Warning 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: A warning when a Switch block directly leads to the next situation without a break;
4.path: Warning when there is a nonexistent path in the classpath, source file path, etc.;
5.serial: A warning when a SERIALVERSIONUID definition is missing on a serializable class;
6.finally: Any warning when the finally clause does not complete properly;
7.all: Warning about all of these conditions.

[1] Annotations (Annotation)--in-depth understanding of Java: Annotations (Annotation) Basic concepts

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.