In depth understanding of Java: annotation (Annotation) Basic concepts

What is annotation (Annotation):

Annotation( annotation ) Namely Java Provides an element in a metaprogram that associates any information with any metadata (metadata) The way and method of .Annotion( annotation ) It's an interface , The program can get the... Of the specified program element through reflection Annotion object , And then through Annotion Object to get the metadata in the annotation .

Annotation( annotation ) yes JDK5.0 And later versions . It can be used to create documents , Tracking dependencies in code , Even perform basic compile time checks . In some ways see ,annotation It's used like a modifier , And applied to packages 、 class type 、 Construction method 、 Method 、 Member variables 、 Parameters 、 In the declaration of a local variable . This information is stored in Annotation Of “name=value” Structural alignment .

Annotation Members of stay Annotation Type is declared as a parameterless method . Its method name and return value are fixed Defines the name and type of the member . There is a specific default syntax here : Allow to declare any Annotation Default value of member : One Annotation Can be name=value No default value is defined for Annotation Members of the value of the , You can also use it name=value To override other member defaults . This is somewhat similar Class , The constructor of the parent class can be the default constructor of the child class , But it can also be covered by subclasses .

Annotation Can be used for a program element ( class 、 Method 、 Member variables, etc ) Associate any information . It should be noted that , There is a The basic rules :Annotation Cannot affect the execution of program code , Whatever the increase 、 Delete Annotation, The code executes consistently . another Outside , Although some annotation adopt java Reflection of api Method is accessed at run time , and java The language interpreter ignores these when it works annotation. It is because of java Virtual machines ignore Annotation, Led to annotation The type in the code is “ It doesn't work ” Of ; It's only through some kind of matching tool that annotation The information in the type is accessed and processed . This article will cover all aspects of the standard Annotation and meta- annotation type , Accompany these annotation The type of tool is java compiler ( Of course, they have to be dealt with in a special way ).

What is? metadata( Metadata ):

Metadata from metadata Translate the word , Namely “ Data about data ” It means .
Metadata has many functions , such as : You may have used Javadoc Note to
Automatically generate documents . This is a kind of metadata function . in general , Metadata can be used to create documents , Tracking code dependencies , Perform compile time format checking , Replace the existing configuration file . If you want to do something about yuan
The role of data is to classify , There is no clear definition yet , But we can depend on what it does , It can be roughly divided into three categories :
1. Document : Generate documents from metadata identified in the code
2. The code analysis : Analyze the code through the metadata identified in the code
3. Compile check : Through the metadata identified in the code, the compiler can realize the basic compilation check
stay Java Meta data exists in the form of tags Java In the code , The existence of metadata tags does not affect the compilation and execution of program code , It's just used to generate other files or to know the description of the code being run at runtime .
in summary :
First of all , Metadata exists in the form of tags Java In the code .
second , Metadata describes information that is type safe , That is to say, the fields inside the metadata all have definite types .
Third , Metadata requires additional processing by tools other than compilers to generate other program components .
Fourth , Metadata can only exist in Java Source code level , It can also exist after compilation Class Inside the document .

Annotation and Annotation type :


Annotation Used in java5.0 The new grammar that it brings , Its behavior is very similar public、final Such a modifier . Every
Annotation Has a name and number of members >=0. Every Annotation The members of have what is called name=value Right name and value ( It's like
javabean equally ),name=value Loaded with Annotation Information about .

Annotation type :

Annotation Type defines Annotation Name 、 type 、 Member defaults . One Annotation
Type can be said to be a special java Interface , Its member variables are restricted , The statement Annotation You need to use a new syntax when typing . When we go through java Reflection api visit
Annotation when , The return value will be an implementation of the
annotation Object of type interface , By accessing this object, we can easily access its Annotation member . Later chapters will refer to java5.0 Of
java.lang It's in the bag 3 A standard Annotation type .

Classification of annotations :

According to the number of annotation parameters , We can divide annotations into three categories :
1. Mark notes : A... Without a member definition Annotation Types are called tag annotations . such Annotation Type only uses its own existence to provide us with information . For example, the following system notes @Override;
2. Single value notes
3. Complete notes

According to the usage and purpose of the notes , We can Annotation Divided into three categories :
1.JDK Built in system notes
2. Yuan notes
3. Custom annotation

Standard annotations are built into the system :

The syntax of annotations is simple , except @ In addition to the use of symbols , He is basically with Java Inherent grammatical consistency ,JavaSE There are three standard annotations built in , It's defined in java.lang in :
@Override: The method used to modify this method covers the method of the parent class ;
@Deprecated: Used to modify outdated methods ;
@SuppressWarnnings: Used to inform java The compiler forbids specific compilation warnings .

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

@Override, Qualify override parent method

It's a tag annotation type , It's used as a way of marking . It shows that the annotated method overloads the method of the parent class , It serves as an assertion . If we use this Annotation In a place where there is no cover
When you cover a method of a parent class method ,java The compiler will alert you with a compilation error . This annotaton It's often powerful when we're trying to override a parent method and we're writing the wrong method name . Usage method
Extremely simple : In the use of this annotation Just add... Before the modified method @Override that will do . The following code is an example of using @Override Modify an attempt to overload
Of the parent class displayName() Method , Examples of spelling mistakes :

public class Fruit {
public void displayName(){
System.out.println(" The name of the fruit is :*****");
} class Orange extends Fruit {
public void displayName(){
System.out.println(" The name of the fruit is : orange ");
} class Apple extends Fruit {
public void displayname(){
System.out.println(" The name of the fruit is : Apple ");
 Orange There won't be any problems with class compilation ,Apple Class will prompt corresponding errors when compiling .@Override Annotations can only be used for methods , Can't be used for other program elements .

@Deprecated, The mark is out of date :

Same as sample Deprecated It's also a tag annotation . When a type or type member uses @Deprecated Embellished words , The compiler will not encourage the use of this tagged program element . And this This modification has a certain “ Continuity ”: If we use this obsolete type or member in our code by inheritance or override , Although inherited or overridden types or members are not declared as @Deprecated, But the compiler still alarms .

It is worth noting that ,@Deprecated This annotation The type and javadoc Medium @deprecated This tag There is a difference : The former is java Compiler recognized , The latter is being javadoc Tools identified to generate documents ( Include why program members have been when 、 A description of how it should be banned or replaced ).

stay java5.0,java The compiler is still looking for... As it was in previous versions @deprecated This javadoc tag, And use them to generate warning messages . But that's going to change in later versions , We should start using it now @Deprecated To modify outdated methods instead of @deprecated javadoc tag.

The following program uses @Deprecated The annotation method is out of date , Also use... In method comments @deprecated tag This method is out of date , The code is as follows :

 class AppleService {
public void displayName(){
System.out.println(" The name of the fruit is : Apple ");
} /**
* @deprecated The method has expired , It is not recommended to use
public void showTaste(){
System.out.println(" The apple taste of fruit is : Crisp and sweet ");
} public void showTaste(int typeId){
System.out.println(" The apple taste of fruit is : Sour and astringent ");
else if(typeId==2){
System.out.println(" The apple taste of fruit is : Miantian ");
System.out.println(" The apple taste of fruit 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 Class showTaste() Method is @Deprecated Labeled obsolete method , stay FruitRun Class , The compiler will say that the method is out of date , Tips not recommended .

SuppressWarnnings, Suppress compiler warnings :

@SuppressWarnings Used to selectively close compiler pairs of classes 、 Method 、 Member variables 、 Warning for variable initialization . stay java5.0,sun Provided javac The compiler gives us -Xlint The choice is to edit The translator warns of legitimate program code , This kind of 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 "unchecked warning" Warning of . Usually when this happens , We need to find the code that caused the warning . If it really means wrong , We need to correct it . For example, if the warning message indicates that our code Of switch Statement does not cover all possible case, Then we should add a default case To avoid this warning .
Sometimes we can't avoid this warning , for example , We
Use must and not generic Old code interactive generic collection Class time , We can't avoid this unchecked
warning. here @SuppressWarning It's going to come in handy , Add... Before the method called @SuppressWarnings modification , Tell the compiler to stop this
Method warning .
SuppressWarning It's not a tag comment . It has a type of String[] Members of , The value of this member is the forbidden warning name . about
javac In terms of compiler , By -Xlint Option valid warning The name is also right @SuppressWarings It works , At the same time, the compiler ignores unrecognized warning names .
annotation Grammar allows in annotation Name followed by parentheses , The brackets are separated by commas name=value Yes, for annotation Member assignments for . Examples are 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 case SuppressWarnings annotation A type only defines a single member , So there's only one simple value={...} As name=value Yes . And because the member value is an array , So that Use braces to declare array values . Be careful : We can abbreviate it in the following case annotation: When annotation Only one member , And the members are named "value=". this You can save "value=". For example, the above method getFruit() Of SuppressWarnings annotation It's abbreviated .

 SuppressWarnings A brief description of the common parameter values for annotations :

1.deprecation: Warnings when using deprecated classes or methods ;
2.unchecked: Warnings when an unchecked conversion is performed , For example, when you use a collection, you don't use generics (Generics) To specify the type of collection save ;
3.fallthrough: When Switch Blocks go directly to the next situation without Break Warning of time ;
4.path: In the classpath 、 Warning when there is a path that does not exist in the source file path, etc ;
5.serial: When missing... On a serializable class serialVersionUID Warning when defining ;
6.finally: whatever finally Warning when clause does not complete properly ;
7.all: Warning about all of the above .

[1] annotation (Annotation)-- In depth understanding of Java: annotation (Annotation) More articles on basic concepts

  1. ( turn ) In depth understanding of Java Annotation type (@Annotation)

    background : Asked questions about annotations during the interview , I've used it in my work java Characteristics of , But there's no deep understanding . Seconds understand ,Java annotation (Annotation) You can learn this way ps: Annotation is the most easy to understand explanation Annotations are a set of metadata , ...

  2. In depth understanding of Java Annotation type (@Annotation)   come from [zejian The blog of ] java The note is in JDK5 A new feature introduced when , Given that most of the boxes are ...

  3. frame foundation : In depth understanding of Java Annotation type (@Annotation)

    The concept of annotation The official definition of annotation First look at the official description of the annotation : An annotation is a form of metadata, that can be added to Java source co ...

  4. understand Java Annotation type

    One . understand Java annotation The essence of annotation is an inheritance Annotation Special interface for , Its concrete implementation class is Java Dynamic agent classes generated at run time . And when we get annotations through reflection , The return is Java Dynamic proxy objects generated at run time $Proxy ...

  5. You really understand Java Comments ?

    You really understand Java Comments ? 1. What is annotation ? Official explanation : Java Comments are used for Java The code provides metadata . As metadata , Annotations don't directly affect your code execution , But there are also some types of annotations that can actually be used for this purpose .Java ...

  6. In depth understanding of Java Annotation principle

    * Use of annotations annotation (Annotation) yes JDK1.5 New features introduced , Included in java.lang.annotation In bag , It's some meta information attached to the code , Associate external information of a class with internal members , Editing translate . ...

  7. In depth understanding of Java annotation

    In depth understanding of Java annotation The content of this paper is based on JDK8. The note is JDK5 Introduced , follow-up JDK Version extended some content , There is no clear indication in this article that the annotations of the versions are JDK5 Just supported annotations .

  8. Java annotation Framework development Java The magic of annotation

    The source of the original text is : locality The benefits of annotation : 1. Be able to read the code written by others , Especially framework related code . 2. It would have required a lot of configuration files , What needs a lot of logic to achieve , You can use one or more annotations instead of , This makes programming ...

  9. java Strengthening the foundation —— In depth understanding of java annotation ( Simple ORM Function realization )

    Catalog 1. What is annotation 2. The structure of annotations and how to read them at run time 2.1 The composition of annotations 2.2 The class hierarchy of annotations 2.3 How to get annotation information at run time 3. Several meta annotations are introduced 3.1 @Retention 3.2 ...

  10. understand java annotation

    @ yes java annotation , namely annotation. Annotation functions can be understood as plug-ins , It's a code level plug-in , Write... On the method of the class :@XXX, Is to insert a plug-in into the code . Java Annotations are bits of meta-information attached to code , For some tools in compilation ...

Random recommendation

  1. Fast cracking hash ciphertext findmyhash

    Fast cracking hash ciphertext findmyhash   Kali Linux Provide a variety of hash ciphertext cracking tools , Such as hashcat.john.rainbows. Either way , It's not easy to crack . Each way takes a lot of time . Crack ...

  2. .NET Core On Mac First step , Configuration environment

    Words .NET Core Come out so long , It's not funny , It's a shame . Since you have chosen to start, you can't give up halfway ..NET Cross platform , Then I'll use Mac Try it . Installation step one : install Homebrew There will be a problem of insufficient authority ...

  3. Flink DataSet API Programming Guide   Example ...

  4. (12)odoo All kinds of lead times and times

    1)Product The lead time of     Customer Lead Time(sale_delay): Customer lead time , finger SO Confirm the number of days to ship to the customer , Due to different sales volume, the time is also different , therefore , Here's an average time .    ...

  5. long-range MSMQ

    brief introduction MSMQ( Microsoft message queue ) yes Windows fuck It is the foundation of message application in the system , It's for creating distributed . Development tools for loosely connected messaging applications . There are many similarities between message queuing and e-mail , They all contain multiple attributes , Used to save messages ...

  6. Google Play Market Research Report

    Inspected Google Play In the Japanese market 10 Application of funds , The focus of the investigation is on each App What are the highlights , Where is the profit model . This article is not App Function introduction of . (1) Anthology of love [ Library applications ] This app includes some love articles , Its main audience is ...

  7. bzoj1832

    In fact, this question is related to bzoj1787 The same, but I use bzoj1787MLE 了 , So it's time to practice on the tree type node=record po,next:longint; end; ..] of node; an ...

  8. How many ways( Memory search )

    How many ways Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) To ...

  9. Delphi edition IP Address and integer are transferred to each other

    Delphi edition IP Address and integer are transferred to each other unit Unit11; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphic ...

  10. [Spark kernel ] The first 34 course :Stage Divide and Task The source code of the best location algorithm is completely decrypted

    Topic of this lesson Job Stage The partition algorithm decrypts Task The best position algorithm realizes decryption introduction The partition algorithm of job scheduling and Task The best position of the algorithm , because Stage The division is DAGScheduler The core of the work , this ...