Deep understanding of Java annotation types (@ annotation)

Java annotation is a new feature introduced in jdk5. Since most frameworks (such as spring) use annotations to simplify code and improve coding efficiency, it is necessary for a java engineer to master and deeply understand annotations. In this article, we will analyze the relevant knowledge points of annotation from the following perspectives

Understanding Java annotations

In fact, Java annotations are not very different from common modifiers (public, static, void, etc.). The following examples are common annotations:

After using @ test annotation on the method, when running the method, the test framework will automatically recognize the method and call it separately, @ test is actually a tag annotation, which plays the role of marking. The runtime tells the test framework that the method is a test method. For @ deprecated and @ suppresswarnings ("uncheck"), they are built-in annotations in Java itself. You can often see them in the code, but this is not a good thing. After all, when there is a @ deprecated annotation on a method or class, it means that the method or class has expired and is not recommended to be reused, @ suppresswarnings means that the specified warning is ignored, For example, @ suppresswarnings ("uncheck"), which is the simplest way to use annotations, let's take a look at the basic syntax of annotation definitions

Basic grammar

Declarative annotation and meta annotation

Let's take a look at how the previous test annotation declares:

We declared the test annotation with @ interface and passed in the ElementType with @ target annotation The method parameter indicates that @ test can only be used on methods, @ retention (retentionpolicy. Runtime) is used to indicate that the annotation lifetime is runtime. From the code point of view, the annotation definition is very similar to the interface definition. Indeed, after all, test will be generated after compilation Class file. For @ target and @ retention, they are meta annotations provided by Java. The so-called meta annotations are annotations that mark other annotations, which are introduced below respectively

@Target is used to constrain where annotations can be applied (such as methods, classes or fields). ElementType is an enumeration type, which is defined as follows and also represents the possible value range

Note that when the annotation does not specify a target value, the annotation can be used on any element. Multiple values are contained by {} and separated by commas, as follows:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>