Basic concepts based on Java annotation (Annotation) _java

Source: Internet
Author: User
Tags deprecated reflection

What is annotation (Annotation):

Annotation (annotation) is Java provides a way and method of associating any information with any metadata (metadata) in the elements of a program. Annotion (annotation) is an interface in which a program can retrieve the Annotion object of a specified program element by reflection, and then obtain the metadata in the annotation by Annotion object.

Annotation (annotations) are 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 applies to packages, types, construction methods, methods, member variables, parameters, and declarations of local variables. 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: Allow the default value of any annotation member to be declared: a annotation can name=value to a annotation member that does not have a defined default value, and of course can use Name= value pairs to override other member defaults. This is somewhat similar to the inheritance attribute of the class, which can be the default constructor of a subclass, but can also be overridden by a quilt class.

Annotation can be used to correlate any information to a program element (class, method, member variable, and so on). It should be noted that there is a basic rule: Annotation can not affect the execution of program code, regardless of adding, deleting Annotation, the code is consistent execution. In addition, while some annotation are accessed through the Java Reflection API method at run time, the Java language interpreter ignores these annotation at work. It is because the Java virtual machine ignores the annotation that the annotation type is "non-functional" in the code, and only through some kind of matching tool will the information in the annotation type be accessed and processed. The standard annotation and meta-annotation types are covered in this article, and the tools that accompany these annotation types are the Java compilers (of course they are handled in a special way).

--------------------------------------------------------------------------------

What is metadata (meta data):

The metadata is translated from the word metadata, which means "data on data".
Metadata has a number of functions, such as: You may have used the annotations of Javadoc to automatically generate documents. This is one of the meta data features. In general, metadata can be used to create documents, track the dependencies of code, perform compile-time format checks, and replace existing configuration files. There is no clear definition of the role of metadata, but we can, according to its role, be broadly divided into three categories:
1. Writing documents: Generating documents from metadata identified in code
2. Code Analysis: Code analysis through the metadata identified in the code
3. Compile check: The metadata identified in the code allows the compiler to achieve basic compilation check
In Java, metadata exists as a label in Java code, and the existence of metadata labels does not affect the compilation and execution of program code, it is only used to generate other files or a needle at runtime to know the description of the code being run.
Sum up:
First, metadata exists in the form of a label in Java code.
Second, the metadata describes the information is type-safe, that is, the fields within the metadata are explicitly typed.
Third, metadata requires tools that are outside the compiler for additional processing to generate other program parts.
Finally, the metadata can exist only at the Java source level, or within the compiled class file.

--------------------------------------------------------------------------------

Annotation and annotation types:

Annotation:

annotation uses the new syntax that comes with java5.0, which behaves much like public and final modifiers. Each annotation has a >=0 name and number of members. The members of each annotation have names and values called Name=value pairs (just like JavaBean), Name=value loaded with 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, its 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, and we can easily access its annotation members by accessing the object. The following sections refer to the 3 standard annotation types included in the Java.lang package in java5.0.

--------------------------------------------------------------------------------

Classification of annotations:

Depending on the number of annotation parameters, we can divide the annotations into three categories:
1. Mark annotation: A annotation type that does not have a member definition is called a tag annotation. This annotation type uses only its own existence or not to provide us with information. For example, the following system annotation @override;
2. Single value annotation
3. Full annotation

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

--------------------------------------------------------------------------------

System built-in standard annotation:

Note syntax is relatively simple, in addition to the use of the @ symbol, he is basically consistent with the Java inherent syntax, javase built-in three standard annotations, defined in the Java.lang:
@Override: A method used to modify the method that overrides the parent class;
@Deprecated: Used to modify methods that are obsolete;
@SuppressWarnnings: Used to tell the Java compiler to prevent specific compilation warnings.

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

--------------------------------------------------------------------------------

@Override, qualify to override the parent class method:

@Override is a tagged annotation type, which is used as a callout method. It demonstrates that the annotated method overloads the parent class and acts as an assertion. If we use this annotation in a method that does not overwrite the parent class method, the Java compiler will alert with a compilation error. This annotaton often works when we try to overwrite the parent method and write the wrong method name. The use of the method is extremely simple: when using this annotation, just precede the modified method with @override. The following code is a displayname () method that uses @override to modify an attempt to overload a parent class with an instance of a misspelling:

Copy Code code as follows:

public class Fruit {

public void DisplayName () {
System.out.println ("The name of the fruit is: * * *");
}
}

Class Orange extends Fruit {
@Override
public void DisplayName () {
System.out.println ("Fruit's name is: Orange");
}
}

Class Apple extends Fruit {
@Override
public void DisplayName () {
System.out.println ("Fruit's name is: Apple");
}
}


There is no problem with the Orange class compilation, and the Apple class prompts the corresponding error at compile time. @Override annotations can be used only for methods and not for other program elements.
--------------------------------------------------------------------------------

@Deprecated, the tag is obsolete:

Likewise deprecated is also a mark annotation. When a type or a member of a type is decorated with @deprecated, 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 inheritance or overwrite, the compiler still has to call the police, although the inherited or overridden type or member is not declared as @Deprecated.

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

The Java5.0,java compiler still looks for @deprecated this Javadoc tag like its previous version and uses them to generate a warning message. But this situation will change in later versions, and we should start using @deprecated now to decorate obsolete methods rather than @deprecated Javadoc tag.

The following procedure uses the @deprecated annotation method to expire, while @deprecated tag is used in the method comment to indicate that the method is obsolete, as follows:

Copy Code code as follows:

Class Appleservice {
public void DisplayName () {
System.out.println ("Fruit's name is: Apple");
}

/**
* @deprecated This method has expired and is not recommended for use
*/
@Deprecated
public void Showtaste () {
System.out.println ("Fruit of the apple taste is: crisp sweet");
}

public void Showtaste (int typeid) {
if (typeid==1) {
System.out.println ("Fruit of the apple taste is: sour");
}
else if (typeid==2) {
System.out.println ("Fruit of the apple taste is: cotton sweet");
}
else{
System.out.println ("Fruit of the apple taste is: crisp 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 @deprecated annotated as an obsolete method, 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 with a selective shutdown compiler warning of classes, methods, member variables, and variable initialization. The Javac compiler provided in Java5.0,sun gives us the-xlint option to warn the compiler of legitimate program code, which in some ways represents a program error. For example, when we use a generic collection class without providing its type, the compiler prompts a warning for "unchecked warning". Usually when this happens, we need to find the code that is causing the warning. If it really represents a mistake, 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 to avoid this warning.
Sometimes we can't avoid this kind of warning, for example, when we use generic collection classes that must interact with generic old code, we can't avoid this unchecked warning. At this point the @suppresswarning is going to come in handy, adding @suppresswarnings adornments before the method is invoked, telling the compiler to stop warning for this method.
Suppresswarning is not a markup annotation. It has a member of type string[] whose value is a prohibited warning name. For the Javac compiler, a warning name that is valid for the-xlint option is also valid for @suppresswarings, while the compiler ignores the unrecognized warning name.
The annotation syntax allows you to assign a value to a member of a annotation by using a comma-separated name=value in the annotation name followed by parentheses. Examples are as follows:

Copy Code code as follows:

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 suppresswarnings annotation type only defines a single member, so there is only one simple value={...} As Name=value pairs. And because the member value is an array, you use curly braces to declare the array value. Note: We can abbreviate annotation in the following cases: When the annotation is only a single member, and the member is named "Value=". At this time can omit "value=". For example, the suppresswarnings annotation of the above method Getfruit () 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 the use;
2.unchecked: Warning When an unchecked conversion is performed, for example, when a collection is used without a generic (generics) to specify the type of the collection save;
3.fallthrough: A warning when the 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: Warning When a serialversionuid definition is missing on a serializable class;
6.finally: Warning of any finally clause not completing properly;
7.all: Warning about all of the above.

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.