Annotations in Java, custom annotations

insert image description here

Framework = Annotations + Reflection + Design Patterns

1. Annotation overview

Annotation ( Annotation) is introduced from JDK5.0, and exists in the code with "@ annotation name".

Annotation can be used like a modifier and can be used to modify declarations of packages, classes, constructors, methods, member variables, parameters, and local variables. You can also add some parameter values, which are stored in the "name=value" pair of Annotation.

Annotations can be loaded during class compilation and runtime to reflect different functions.

2. Notes and Notes

Annotation can also be regarded as a kind of annotation. By using Annotation, some supplementary information can be embedded in the source file without changing the original logic. However, annotations are different from single-line comments and multi-line comments.

  • For single-line comments and multi-line comments, it is for programmers to see.
  • Annotations can be read by compilers or other programs. The program can also make corresponding processing according to different annotations.

3. The importance of annotations

In JavaSE, the purpose of using annotations is relatively simple, such as marking obsolete functions, ignoring warnings, etc. Annotations play a more important role in JavaEE/Android, for example, to configure any aspect of the application, replacing the cumbersome code and XML configuration left in the old version of JavaEE.

Future development models are based on annotations, JPA is based on annotations, Spring 2.5 and above are based on annotations, Hibernate 3.x and later are also based on annotations, and part of Struts2 is also based on annotations.

4. Common Annotation functions

4.1 Generate documentation-related annotations

@author: Indicate the author who developed this type of module, used among multiple authors, split
@version: Indicate the version of this type of module
@see: Reference direction, that is, related topics
@since: From which version is added
@param: Description of a parameter in the method, if there is no Parameters cannot be written
@return: Description of the return value of the method. If the return value type of the method is void, it cannot be written
@exception: Description of the exception that the method may throw. If the method does not explicitly throw an exception using throws, it cannot be written.

4.2 Format check at compile time (three basic annotations built into JDK)

@Override: Restricted to rewrite the parent class method, this annotation can only be used for methods

  • It is used to detect that the marked method is a valid rewriting method, if not, a compilation error will be reported!
  • Can only be marked on methods.
  • It will be read by the compiler program.

@Deprecated: Used to indicate that the decorated element (class, method, etc.) is obsolete. Usually because the modified structure is dangerous or better alternatives exist

  • Used to indicate that the marked data is outdated and not recommended.
  • Can be used to modify properties, methods, structures, classes, packages, local variables, parameters.
  • It will be read by the compiler program.
    @SuppressWarnings: suppress compiler warnings
  • Suppress compilation warnings. When we don't want to see warning messages, we can use SuppressWarningsannotations to suppress warning messages
  • Can be used to modify classes, properties, methods, structures, local variables, parameters
  • It will be read by the compiler program.
  • The warning types that can be specified are (understand)
    • all, to suppress all warnings
    • unchecked, to suppress warnings related to unchecked jobs
    • unused, to suppress warnings about unused and disabled code
    • deprecation, to suppress and eliminate related warnings
    • nls, to suppress warnings related to non-nls string literals
    • null, to suppress warnings related to null analysis
    • rawtypes, to suppress warnings related to using raw types
    • static-access, to suppress warnings related to incorrect static access
    • static-method, to suppress warnings related to methods that might be declared static
    • super, to suppress warnings related to substitution methods but not super calls

5. Meta annotations

JDK1.5 defines four standard meta-annotationtypes in the java.lang.annotation package, which are used to provide descriptions for other annotation types.

(1) @Target: Used to describe the scope of use of annotations

  • ElementTypeCan be specified by 10 constant objects of enumeration type
  • TYPE,METHOD,CONSTRUCTOR,PACKAGE…

(2) @Retention: Used to describe the life cycle of annotations

  • RetentionPolicyCan be specified by 3 constant objects of enumeration type
  • SOURCE (source code), CLASS (bytecode), RUNTIME (runtime)
  • Only the RUNTIME phase can be read by reflection.

(3) @Documented: Indicates that this annotation should be recorded by the javadoc tool.
(4) @Inherited: Allow subclasses to inherit annotations from parent classes

Sample code:

package java.lang;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
    
    
}
package java.lang;

import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;

@Target({
    
    TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    
    
    String[] value();
}
package java.lang;

import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={
    
    CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
    
    
}

6. Custom annotations

A complete annotation should contain three parts: (1)声明, (2)使用,(3)读取

Declare custom annotations:

【元注解】
【修饰符】 @interface 注解名{
    
    
    【成员列表】
}
  • Custom annotations can use four meta-annotations @Retention, @Target, @Inherited, @Documentedto indicate its life cycle, usage location, whether it is inherited, and whether it is generated into the API document.
  • AnnotationMembers of are declared in Annotationthe definition as an abstract method with no parameters and a return value, which we also call configuration parameters. The return value type can only be an array of eight basic data types, Stringtype, Classtype, enumtype, Annotationtype, and all of the above types
  • You can specify a default return value for an abstract method using defaultthe keyword
  • If the defined annotation contains an abstract method, the return value must be specified when used, unless it has a default value. The format is "method name = return value". If there is only one abstract method that needs to be assigned a value, and the method name is value, "value=" can be omitted. Therefore, if the annotation has only one abstract method member, it is recommended to use the method name value.

6.1 Define custom annotations

import java.lang.annotation.*;

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    
    
    String value();
}
import java.lang.annotation.*;

@Inherited
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    
    
    String columnName();
    String columnType();
}

6.2 Using custom annotations

@Table("t_stu")
public class Student {
    
    
    @Column(columnName = "sid",columnType = "int")
    private int id;

    @Column(columnName = "sname",columnType = "varchar(20)")
    private String name;
}

6.3 Reading and processing custom annotations

Custom annotations must be accompanied by the information processing flow of annotations to be meaningful.

Annotations defined by yourself can only be read using reflected code. So the declaration cycle of the custom annotation must be RetentionPolicy.RUNTIME.

Guess you like

Origin blog.csdn.net/weixin_43847283/article/details/130174137