Many Java programmers have little or no understanding of Java annotations, or even what annotations are

In this article, we use the simplest demo, the most popular and shortest language, take you to understand what annotations are?

Just to recap the basics, we know that Java source files are edited to generate.class files,

  1. .JavaSource file, this isSource file period
  2. The source file is generated after compilation.classBytecode files, this one tooCompile time
  3. .classLoad it into memory, and it’s ready to use. This isDuring the period of running

The following figure

With that in mind, the next step is to talk about annotations. Let’s talk about annotations formally. This article will cover annotations from the following two aspects

  • What are annotations
  • How to define an annotation
  • How to use annotations

Especially the third one, a lot of people don’t understand the annotations, because they don’t know how to use the third one and this article will use the simplest language to reveal how to use the annotations, right

What is a note?

In a word, annotations are the same as labels in life, such as a person, this person may have a student label, a moonlight clan label, a love of the bar label

How to define a annotation

@interface {} @interface {} @interface {} @interface {} @interface {} @interface {} @interface {} @interface {

For example, to define an annotation named info, create a new file called info.java as follows:

package com.demo;

// Defines an annotation called info
public @interface info {

}
Copy the code

It’s pretty simple. There’s an annotation called info. There are two questions

  • First: Where is the INFO annotation used? Is it the class name? Or is it for a class field? Or does it apply to class methods?

  • Second: Info annotation life cycle (or retention policy, I prefer life cycle) Annotations have a life cycle? The answer is yes, of course

    As mentioned earlier, annotation is similar to the label, a person may have just graduated, moonlight clan label, just graduated to earn less

    But it is possible that after 3 or 4 years, the technology is good, the salary went up, there may be no moonlight clan label

    So how many life cycles do tags have? The answer is: 3, respectively is the source file, compile time, run time

That is, some annotations exist at source time, some tags exist at compile time, and some tags exist at run time

::: tip Run-time annotations are used most frequently. This article focuses on run-time, source-time, and compile-time

The runtime, or annotations, still exist at runtime:

We then define the INFO annotation to be used on the fields of the class and to exist at run time

First on the code, and then explain, the code is as follows:

@Target(ElementType.FIELD)          // Annotations apply to class fields
@Retention(RetentionPolicy.RUNTIME) // Annotations exist at runtime
public @interface info {
    
}
Copy the code

As you can see from the code above, there’s an @target @retention annotation, so what is @target @retention? A: @target and @Retention are meta-annotations, which can be interpreted as meta-annotations: meta-annotations are the original meaning of the meta-annotations. A simple example to help understand what meta-annotations are

For example, if you develop an IOS APP and use Xcode to develop it, what is xcode developed with? Define an annotation, using the meta annotation is not very similar, as shown below

Seen above figure should be able to understand, what is yuan notes, is to define annotations, know how to use it We develop software, for example, to use all kinds of developing software IDE, we don’t have to tube these IDE which software is software development We just need to know, yuan annotation is equivalent to the IDE, Annotations are equivalent to the software we developed, and that’s fine

Going back to the above definition of info, let’s explain the use of the two annotations Target and Retention and what values they can take

Target yuan notes

Use: Defines where an annotation is to be used, such as on a class, field, method, etc. Let’s just list a few of the most common ones, and the rest of them can be sorted out by ourselves, Where the following | | values with | | – | – | – | | ElementType. TYPE | | on a class or interface | ElementType. The FIELD class | | on the FIELD of | ElementType. METHOD | | methods of a class | ElementType. PARAMETER | | on the method of PARAMETER

The Retention yuan notes

Usage: Defines the annotation lifecycle (or retention policy, I prefer lifecycle). Only three, the following | | values which exist in the period of | | – | – | – | | RetentionPolicy. SOURCE | phase SOURCE file | | RetentionPolicy. CLASS | compile-time | | RetentionPolicy. RUNTIME | | SOURCE running period

The meta annotations are defined, we just use them, we just know how to use them, we only use meta annotations when we customize a annotation, take a few values, define where our annotation will be used, the period of time, and so on, and that’s it:


So let’s summarize this a little bit

  • Annotations are things like labels
  • Annotation definitions are usedPublic @interface Annotation name {}
  • Annotations have a place and a life cycle
  • Annotations can be used on classes, fields, methods, parameters, etc
  • Meta annotations are used to define annotations, just as Xcode is used to develop IOS software

Third and most important, we’ve learned how to customize annotations. How to use them?

How to use annotations

If you don’t understand reflection, you should read the following two articles. First, you should read the following article

Let’s extend the above info annotation as follows:

@Target(ElementType.FIELD)          // Annotations apply to class fields
@Retention(RetentionPolicy.RUNTIME) // Annotations exist at runtime
public @interface info {
    String job(a);       / / the job properties
    String comment(a);   / / comment properties
}
Copy the code

Right, so again you see annotations can define properties, so remember, just follow the definition above. Basically see how to use

We define a Worker class Worker as follows:

/ / worker class
public class Worker {
    // The worker's name
    public String name;

    // Print the basic information of the job
    public void show(a){}}Copy the code

For a simple class, we add our defined info annotation to the name field, as follows

public class Worker {

    // Annotations can be used to pass values to attributes, echoing those defined in comment and info
    @info(job = "engineer ",comment =" work hard ") 
    public String name;

    public void show(a){}}Copy the code

Above we added our own annotation to the name field, and passed in the annotation the job title is: Engineer, and the evaluation is: Hard working. We want to print the job name, title, and evaluation in the show() method

The job and comment in the annotation can be obtained by reflection. Note the comment below

public class Worker {

    // Annotations can be passed to attributes, job and comment correspond to the definition
    @info(job = "engineer ",comment =" work hard ")
    public String name;

    public void show(a){
        //1 gets the bytecode of this class
        Class clz = this.getClass();

        //2 Gets the fields defined in the class
        Field[] fields = clz.getDeclaredFields();

        //3 Iterate over the fields to see which fields have info annotations
        for (Field field : fields){
            //4 Check whether there is an INFO annotation on this field
            info annotation = field.getAnnotation(info.class);

            //5 If the value is not null, the field has an INFO annotation
            if(annotation ! =null) {//6 Obtain the job and comment in the INFO comment
                String job = annotation.job();
                String comment = annotation.comment();

                //7 print out
                System.out.println("I am." + this.name + "My position is:" + job + "My assessment is:"+ comment); }}}}Copy the code

As you can see from the above, the steps for using annotations are as follows:

  1. Gets the Class of the Class, which is the bytecode of the Class
  2. Gets an array of character codes for all fields of a class
  3. Through field
  4. throughinfo annotation = field.getAnnotation(info.class) Gets the corresponding annotation on the field
  5. Get the value passed in the annotation through the annotation

Let’s write another main function that calls the above code

public class Demo1 {
    public static void main(String[] args){
        Worker worker = new Worker();
        worker.name = "Waiting for the rabbit,www.helloworld.net webmaster"; worker.show(); }}Copy the code

Print the following:

I am: treat rabbit,www.helloworld.net stationmaster my position is: engineer my evaluation is: work very hard

This article to this, almost finished, annotation of many other things also did not speak, but is not important, this article is the most important to let you know what comments, how to define the annotations, how to use annotations As for the comments of other knowledge, such as how to use annotations on the method, with the class, and so on, are similar, only need to check it. Many articles on the Internet, as long as you can understand the annotations through this article, understand the other annotations is simple.