This is the sixth day of my participation in Gwen Challenge

This article is participating in “Java Theme Month – Java Development in Action”, see the activity link for details

What are annotations

Attention! A comment is an explanation of the code, not a comment. A comment is an explanation of the code when you write it, and both serve to explain the code

1. The concept

Starting with JDK5,Java has added support for metadata, also known as annotations. Annotations are somewhat different from annotations and can be understood as special tags in code that can be read and processed at compile, class load, and run time. Annotations allow developers to embed supplementary information in source code without changing the original code and logic. — Baidu Encyclopedia

In Java, annotations start with an @ sign. They are read at compile time, class load time, run time, and then processed by an annotation handler. Annotations simply store metadata and do not modify the code that modifiers the object

Source of 2.

In notes before has not yet appeared, generally using XML file to store metadata, profile information and SQL statements can be regarded as metadata, metadata, and code that makes the coupling is very low, if the project is very big, can cause maintenance difficulties, so he was born the annotations and let the metadata and code together, Greatly reduced the programming complexity, in the future, annotation capabilities are not limited to binding metadata annotations are really useful, who knows

3. Classification of annotations

  1. JDK built-in annotations
  2. Comments from third-party frameworks
  3. Custom annotations

2. Custom annotations

In the above three types of annotations, we focus on custom annotations

1. Yuan note

Meta-annotations are used in custom annotations. There are four meta-annotations, namely @target, @Retention, @Inherited, and @Documented

@Target

This annotation represents the scope of the custom annotation. That is, the annotation indicates what type of class, property, or method the defined annotation can be used to modify

Here is a list of values for @target. You don’t need to remember them, just look them up

The values Annotation scope
METHOD Can be used methodically
TYPE Can be used on classes or interfaces
ANNOTATION_TYPE Available on annotation types (types modified by @interface)
CONSTRUCTOR Can be used on constructors
FIELD Can be used on domains, namely class properties/fields
LOCAL_VARIABLE It can be used on local variables, which are properties inside methods
PACKAGE Used to record package information for Java files
PARAMETER Can be used on parameters

Value of @Target in @Resource

@Target({TYPE, FIELD, METHOD})
Copy the code

@Retention

This annotation represents the life cycle of the custom annotation, that is, the annotation determines at which stage the custom annotation can be processed and at which stage it can exist

The following is the value table of **@Retention **, ditto above

The values The life cycle
RetentionPolicy.SOURCE It only lives on.java files, it doesn’t live on.class files, it doesn’t exist once it’s compiled by the compiler
RetentionPolicy.CLASS It can live in a.class file, it doesn’t live at runtime, in memory, but it doesn’t exist after it goes through the class loader
RetentionPolicy.RUNTIME The ability to live in memory, whether through the compiler or the classloader, is often used for custom annotations

The value of @Retention in @Resource

@Retention(RUNTIME)
Copy the code

@Inherited

This annotation allows A subclass to inherit annotations from its parent class, so for example, A inherits from B, and B has this annotation and other annotations, so class A inherits other annotations from class B. But the child interface inheritance and implementation does not have the parent interface annotation that has no value, just use it

@Documented

This annotation indicates that we do not need information about the custom annotation to be included in the annotated class when generating javadoc. There are many ways to generate javadoc documents, using the IDEA, javadoc.exe command line

2. Custom annotation syntax

  1. Use the @interface keyword definition in the same way you use class, interface, enum, etc
  2. Define an Annotation Type Element

Defining the annotation type element is our focus. First, the element’s access modifier must be public. Second, the types of elements can only be basic data types (String, int, Class, etc.) and enumerations. Third, if there is only one element, the element name is value. Fourth, add **() after the element name; Fifth, you can add default after (), followed by the default value **

Here’s the @Retention annotation for example

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value(a);
}
Copy the code

3. Custom annotations

Scenario: A Table similar to a database

/ * * *@authorXXJ * table notes */
@Target({TYPE})
@Retention(RUNTIME)
public @interface Table {
    String value(a);
}
Copy the code

Column

/ * * *@authorXXJ * line notes */
@Target(LOCAL_VARIABLE)
@Retention(RUNTIME)
public @interface Column {
    String value(a);
}
Copy the code

4. Use custom annotations

Annotations are defined, and of course annotations are used, and there’s reflection, and if you don’t know it, look at my [Java], reflection is literally the essence of Java

First, define a User class

/ * * *@authorXXJ * User table */
@Table("User")
public class User implements Serializable {
    @Column("name")
    private String name;
    @Column("age")
    private Integer age;
    public User(a) {}//get, set, toString
}
Copy the code

Then, the most important thing to write a Dome test class is the explainAnnotation() method, if you know about reflection

/ * * *@authorXXJ * Annotation parsing test */
public class Demo {
    public static void main(String[] args) {
        User user=new User();
        user.setName("xiaoming");
        user.setAge(18);
        User user1=new User();
        user1.setName("xiaohong");
        // Call the method to parse the annotation
        explainAnnotation(user);
        explainAnnotation(user1);
    }
    private static void explainAnnotation(Object object){
        // Define a String to hold information
        String str="";
        Class obClass=object.getClass();
        // Check if it is a Table annotation
        if(! obClass.isAnnotationPresent(Table.class)){return;
        }
        // Get table annotation information
        Table table= (Table) obClass.getAnnotation(Table.class);
        // Get the value of the table annotation
        String tableName=table.value();
        str+="tableName="+tableName;
        // Get the attributes/fields of the object class
        Field[] fields=obClass.getDeclaredFields();
        // Loop through attributes
        for (Field field:fields) {
            // Check if it is Column annotation
            if(! field.isAnnotationPresent(Column.class)){continue;
            }
            // Get the column annotation information
            Column column= field.getAnnotation(Column.class);
            // Get the value of the column annotation
            String columnName=column.value();
            // Concatenate the getXxx() method name for the corresponding property
            String getMethodName="get"+columnName.substring(0.1).toUpperCase()
                    +columnName.substring(1);
            // Define an object to hold the value
            Object fieldValue = null;
            try {
                // Get the corresponding property's getXxx() method
                Method method=obClass.getMethod(getMethodName);
                // Call the method
                fieldValue=method.invoke(object);
            }catch (Exception e){}
            // Concatenates a string
            str+=","+columnName+":"+fieldValue; } System.out.println(str); }}Copy the code

As you can see, the contents of the annotation can be obtained directly from the class class, but the property values of the object can only be obtained from the object, so use Method.invoke (object) and pass the object to get the property values of the object

Third, summary

From the above custom annotations and parsing custom annotations, we can see that the creation of a custom annotation, not directly use it to have effect, but to write another method to parse the annotation, and then according to the parsing of the annotation content in the corresponding operation. MyBatis provides @mapper annotation to determine whether the class has @mapper annotation, and @select value can be directly used to concatenate SQL statements.

— — — — — — — — — — — — — — —

The more you know, the more you don’t know.

If you have any questions about the content of this article, please comment directly or email me. If you think it’s good, a “like” is a sign of support

Shall not be reproduced without permission!

Wechat search [programmer Xu Xiaobai], attention can be the first time to read the latest article. There are 50 high-frequency school recruitment interview questions prepared by me, as well as a variety of learning materials.