What is annotation:
Annotation (annotation) is a way and method provided by Java to associate any information and any metadata (metadata) with elements in the metaprogram. Annotation (annotation) is an interface. The program can obtain the Annotation object of the specified program element through reflection, and then obtain the metadata in the annotation through the Annotation object.
Annotation (annotation) is introduced in JDK5.0 and later versions. It can be used to create documentation, track dependencies in your code, and even perform basic compile-time checks. In some ways, annotations are used like modifiers and are applied to the declaration of packages, types, constructors, methods, member variables, parameters, and local variables. This information is stored in the "name=value" structure pair of Annotation.
The members of an Annotation are declared as parameterless methods in the Annotation type. Its method name and return value define the name and type of the member. There is a specific default syntax here: it is allowed to declare the default value of any Annotation member: an Annotation can use a name=value pair as the value of an Annotation member that does not define a default value. Of course, a name=value pair can also be used to override the default value of other members. value. This is somewhat similar to the inheritance characteristics of classes. The constructor of the parent class can be used as the default constructor of the subclass, but it can also be overridden by the subclass.
Annotation can be used to associate any information with 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 whether annotation is added or deleted, the code will be executed consistently. In addition, although some annotations are accessed at runtime through Java's reflection API methods, the Java language interpreter ignores these annotations while working. It is precisely because the Java virtual machine ignores Annotation that the annotation type "does not work" in the code; the information in the annotation type can only be accessed and processed through some supporting tools. This article will cover the standard Annotation and meta-annotation types. The tool that accompanies these annotation types is the Java compiler (which of course handles them in some special way).
-------------------------------------------------- ----------------------------------
What is metadata (metadata):
Metadata is translated from the word metadata, which means "data about data".
Metadata has many functions. For example, you may have used Javadoc comments to automatically generate documentation. This is one type of metadata function. In general, metadata can be used to create documentation, track code dependencies, perform compile-time format checks, and replace existing configuration files. If we want to classify the role of metadata, there is currently no clear definition, but we can roughly divide it into three categories based on its role:
1. Writing documents: Generating documents through the metadata identified in the code 2. Code analysis: Analyzing the code through the metadata identified in the code 3. Compilation check: Using the metadata identified in the code, the compiler can achieve basic compilation Check that metadata in Java exists in the Java code in the form of tags. The existence of metadata tags does not affect the compilation and execution of the program code. It is only used to generate other files or to know the code being run at runtime. Descriptive information.
In summary:
First, metadata exists in the Java code in the form of tags.
Second, the information described by metadata is type-safe, that is, the fields within the metadata have clear types.
Third, metadata requires additional processing by tools other than the compiler used to generate other program components.
Fourth, metadata can only exist at the Java source code level, or it can exist inside the compiled Class file.
-------------------------------------------------- ----------------------------------
Annotation and Annotation types:
Annotation:
Annotation uses the new syntax brought in java5.0, and its behavior is very similar to modifiers such as public and final. Each Annotation has a name and the number of members >=0. Each member of an Annotation has a name and value called a name=value pair (just like a javabean), and name=value loads the information of the Annotation.
Annotation type:
The Annotation type defines the name, type, and member default value of the Annotation. An Annotation type can be said to be a special Java interface. Its member variables are restricted, and new syntax is required when declaring an Annotation type. When we access Annotation through the Java reflection API, the return value will be an object that implements the annotation type interface. By accessing this object, we can easily access its Annotation members. The following chapters will mention the three standard Annotation types included in the java.lang package of java5.0.
-------------------------------------------------- ----------------------------------
Annotation categories:
According to the number of annotation parameters, we can divide annotations into three categories:
1. Mark annotation: An Annotation type without member definition is called a mark annotation. This Annotation type only uses its own presence or absence to provide us with information. For example, the following system annotation @Override;
2. Single value annotation 3. Complete annotation
According to the usage and purpose of annotations, we can divide Annotations 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, it is basically consistent with the inherent syntax of Java. There are three standard annotations built into JavaSE, which are defined in java.lang:
@Override: Used to modify this method to override the method of the parent class;
@Deprecated: used to modify obsolete methods;
@SuppressWarnings: Used to notify the Java compiler to suppress specific compilation warnings.
Let's take a look at the functions and usage scenarios of the three built-in standard annotations in turn.
-------------------------------------------------- ----------------------------------
@Override, restrict overriding parent class methods:
@Override is a marker annotation type that is used to annotate methods. It shows that the annotated method overloads the method of the parent class and plays the role of assertion. If we use this kind of Annotation in a method that does not override the parent class method, the Java compiler will warn you with a compilation error. This annotation often comes into play when we try to override a parent class method but write the wrong method name. The usage is extremely simple: when using this annotation, just add @Override in front of the modified method. The following code is an example of using @Override to modify the displayName() method of an attempt to override the parent class, but there are spelling errors:
public void displayName(){
System.out.println("The name of the fruit is: *****");
}
}
class Orange extends Fruit {
@Override
public void displayName(){
System.out.println("The name of the fruit is: orange");
}
}
class Apple extends Fruit {
@Override
public void displayname(){
System.out.println("The name of the fruit is: Apple");
}
}
@Deprecated, the tag is deprecated:
Similarly, Deprecated is also a markup annotation. When a type or type member is decorated with @Deprecated, the compiler will discourage the use of this annotated program element. And this kind of modification has a certain degree of "continuity": if we use this outdated type or member in the code through inheritance or overwriting, although the inherited or overridden type or member is not declared @Deprecated, The compiler still has to warn you.
It is worth noting that there is a difference between the @Deprecated annotation type and the @deprecated tag in javadoc: the former is recognized by the java compiler, while the latter is recognized by the javadoc tool and used to generate documentation (including why program members are obsolete, and its description of how it should be prohibited or replaced).
In Java 5.0, the Java compiler still looks for the @deprecated Javadoc tags and uses them to generate warning messages as it did in previous versions. But this situation will change in subsequent versions, and we should start using @Deprecated now to decorate deprecated methods instead of @deprecated javadoc tag.
In the following program, the @Deprecated annotation is used to mark the method as expired. At the same time, the @deprecated tag is used in the method annotation to mark the method as expired. The code is as follows:
/**
* @deprecated This method has expired and is not recommended.
*/
@Deprecated
public void showTaste(){
System.out.println("The taste of fruity apples is: crisp and sweet");
}
public void showTaste(int typeId){
if(typeId==1){
System.out.println("The taste of fruit apple is: sour");
}
else if(typeId==2){
System.out.println("The taste of fruity apples is: sweet");
}
else{
System.out.println("The taste of fruity apples is: crisp and 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);
}
}
-------------------------------------------------- ----------------------------------
SuppressWarnings, suppress compiler warnings:
@SuppressWarnings is used to selectively turn off compiler warnings for classes, methods, member variables, and variable initialization. In java5.0, the javac compiler provided by sun provides us with the -Xlint option to enable the compiler to warn against legal program code. This warning represents a program error to some extent. For example, when we use a generic collection class without providing its type, the compiler will prompt an "unchecked warning" warning. Usually when this happens, we need to find the code that caused the warning. If it truly represents an error, we need to correct it. For example, if the warning message indicates that the switch statement in our code does not cover all possible cases, then we should add a default case to avoid this warning.
Sometimes we cannot avoid this warning. For example, we cannot avoid this unchecked warning when we use a generic collection class that must interact with non-generic old code. At this time, @SuppressWarning will come in handy. Add @SuppressWarnings modification before the called method to tell the compiler to stop warning about this method.
SuppressWarning is not a markup annotation. It has a member of type String[], the value of this member is the forbidden warning name. For the javac compiler, warning names that are valid for the -Xlint option are also valid for @SuppressWarings, and the compiler ignores unrecognized warning names.
The annotation syntax allows the annotation name to be followed by parentheses. In the parentheses are comma-separated name=value pairs used to assign values to the members of the annotation. Examples are as follows:
@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>();
}
}
A brief description of common parameter values annotated by SuppressWarnings:
1.deprecation: Warning when deprecated classes or methods are used;
2. unchecked: Warning when unchecked conversion is performed, for example, when using a collection, generics are not used to specify the type of collection saved;
3.fallthrough: Warning when the Switch program block leads directly to the next situation without Break;
4.path: Warning when there are non-existent paths in the class path, source file path, etc.;
5.serial: Warning when serialVersionUID definition is missing on a serializable class;
6.finally: Warning when any finally clause cannot be completed normally;
7.all: Warning about all the above situations.