Home >Java >javaTutorial >In-depth understanding of Java: basic concepts of annotation

In-depth understanding of Java: basic concepts of annotation

巴扎黑
巴扎黑Original
2017-06-26 09:18:321309browse

What is annotation (Annotation):

Annotation (annotation) is that Java provides a way and method for elements in a metaprogram to associate any information and any metadata (metadata). 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 Annotation are declared in the form of 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 certain 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 documents. 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: Generated through metadata identified in the code Documentation
2. Code analysis: Analyze the code through the metadata identified in the code
3. Compilation check: The metadata identified in the code allows the compiler to implement basic compilation checks
In Java Metadata exists in Java code in the form of tags. The existence of metadata tags does not affect the compilation and execution of program code. It is only used to generate other files or to know the description information of the code being run at runtime.
In summary:
First, metadata exists in 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 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 type:

Annotation:

Annotation uses the new syntax brought in java5.0, and its behavior is very similar to public and final such modifier. 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 needs to be used when declaring the 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.


Classification of annotations:

Based on the number of annotation parameters, we can divide annotations into three categories:
1. Marker 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 annotation usage and purpose, 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 In addition, 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 cover 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, limited to overriding parent class methods:

@Override is a mark annotation type, which is used as an annotation method. 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:

In-depth understanding of Java: basic concepts of annotation
public class Fruit {

    public void displayName(){
        System.out.println("水果的名字是:*****");
    }
}

class Orange extends Fruit {
    @Override
    public void displayName(){
        System.out.println("水果的名字是:桔子");
    }
}

class Apple extends Fruit {
    @Override
    public void displayname(){
        System.out.println("水果的名字是:苹果");
    }
}
In-depth understanding of Java: basic concepts of annotation
  Orange 类编译不会有任何问题,Apple 类在编译的时候会提示相应的错误。@Override注解只能用于方法,不能用于其他程序元素。

@Deprecated, the tag is obsolete:

Similarly, Deprecated is also a tag 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 "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 as @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 documents (including programs A description of why the member is obsolete and how it should be banned or replaced).

In Java 5.0, the Java compiler still looks for the @deprecated javadoc tags like its previous versions and uses them to generate warning messages. But this situation will change in subsequent versions, and we should start using @Deprecated to decorate deprecated methods now instead of @deprecated javadoc tag.

In the following program, the @Deprecated annotation is used to indicate that the method has expired. At the same time, the @deprecated tag is used in the method annotation to indicate that the method is obsolete. The code is as follows:

In-depth understanding of Java: basic concepts of annotation
 class AppleService {
    public void displayName(){
        System.out.println("水果的名字是:苹果");
    }
    
    /**
     * @deprecated 该方法已经过期,不推荐使用
     */
    @Deprecated
    public void showTaste(){
        System.out.println("水果的苹果的口感是:脆甜");
    }
    
    public void showTaste(int typeId){
        if(typeId==1){
            System.out.println("水果的苹果的口感是:酸涩");
        }
        else if(typeId==2){
            System.out.println("水果的苹果的口感是:绵甜");
        }
        else{
            System.out.println("水果的苹果的口感是:脆甜");
        }
    }
}

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);
    }

}
In-depth understanding of Java: basic concepts of annotation

  AppleService类的showTaste() 方法被@Deprecated标注为过时方法,在FruitRun类中使用的时候,编译器会给出该方法已过期,不推荐使用的提示。


SuppressWarnnings,抑制编译器警告:

  @SuppressWarnings 被用于有选择的关闭编译器对类、方法、成员变量、变量初始化的警告。在java5.0,sun提供的javac编译器为我们提供了-Xlint选项来使编译器对合法的程序代码提出警告,此种警告从某种程度上代表了程序错误。例如当我们使用一个generic collection类而又没有提供它的类型时,编译器将提示出"unchecked warning"的警告。通常当这种情况发生时,我们就需要查找引起警告的代码。如果它真的表示错误,我们就需要纠正它。例如如果警告信息表明我们代码中的switch语句没有覆盖所有可能的case,那么我们就应增加一个默认的case来避免这种警告。
  有时我们无法避免这种警告,例如,我们使用必须和非generic的旧代码交互的generic collection类时,我们不能避免这个unchecked warning。此时@SuppressWarning就要派上用场了,在调用的方法前增加@SuppressWarnings修饰,告诉编译器停止对此方法的警告。
  SuppressWarning不是一个标记注解。它有一个类型为String[]的成员,这个成员的值为被禁止的警告名。对于javac编译器来讲,被-Xlint选项有效的警告 名也同样对@SuppressWarings有效,同时编译器忽略掉无法识别的警告名。
  annotation语法允许在annotation名后跟括号,括号中是使用逗号分割的name=value对用于为annotation的成员赋值。实例如下:

In-depth understanding of Java: basic concepts of annotation
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>();
    }
}</string></string></fruit></fruit></fruit></fruit>
In-depth understanding of Java: basic concepts of annotation

  在这个例子中SuppressWarnings annotation类型只定义了一个单一的成员,所以只有一个简单的value={...}作为name=value对。又由于成员值是一个数组,故使用大括号来声明数组值。注意:我们可以在下面的情况中缩写annotation:当annotation只有单一成员,并成员命名为"value="。这时可以省去"value="。比如将上面方法getFruit()的SuppressWarnings annotation就是缩写的。

   SuppressWarnings注解的常见参数值的简单说明:

    1.deprecation:使用了不赞成使用的类或方法时的警告;
    2.unchecked:执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型; 
    3.fallthrough:当 Switch 程序块直接通往下一种情况而没有 Break 时的警告;
    4.path:在类路径、源文件路径等中有不存在的路径时的警告; 
    5.serial:当在可序列化的类上缺少 serialVersionUID 定义时的警告; 
    6.finally:任何 finally 子句不能正常完成时的警告; 

    7.all:关于以上所有情况的警告。

学习Java的同学注意了!!!
学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群:159610322   我们一起学Java!

The above is the detailed content of In-depth understanding of Java: basic concepts of annotation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn