Together to learn Java annotations (Annotation) together to learn Java annotations (Annotation)

Together to learn Java annotations (Annotation)

 

A. What is Annotation

We see a lot of code, such as @ Override, @ SuppressWarnings, @ Test annotation like pattern is in the usual development process, annotations are placed class, constructors, methods, properties, before the parameter marker.

Two. Annotation role

To a class, method .. add a comment, this link is only made a mark, and the code itself will not have any impact, requiring subsequent links with, other methods require the notes given business logic processing. Just as we have made a shared positioned on the micro-channel, and at this time there is no use, only when other people are back into the shared location, distance to clear between us, to know how to get together.

Notes divided into three categories:

2.1 compiler uses to comment

Such as @ Override, @ SuppressWarnings are used by the compiler to comment, it is to tell the compiler something, without going into .class compiled files.

@Override: tell the compiler to rewrite the method to check whether the parent class;

@SuppressWarnings: tell the compiler to ignore the warnings section of the generated code;

For developers, it is used directly without further action

2.2 .class files to notes

Need to make some modifications to the annotated bytecode .class files by the tool, the tool will be set when some class loading, dynamic modification denoted by a .class file annotation, to achieve some special features, a one-time treatment is completed, does not exist in memory, are very low-level tool library, the framework will use for developers, generally not involved.

Notes 2.3 runtime read

Has been present in the JVM, the notes can be read during operation, is the most commonly used annotation, such as the Spring @ Controller, @ Service, @ Repository, @ AutoWired, Mybatis of @ Mapper, Junit of @Test, etc., these notes many tools are custom frameworks play a special role during operation notes, general developers can also customize this type of comment.

III. Definitions Annotation

@Interface we use to define a comment

/**
 * 定义一个Table注解
 */
public @interface Table {
    String value() default ""; }
/**
 * 定义一个Colum注解
 */
public @interface Colum {
    String value() default ""; String name() default ""; String dictType() default ""; }

This will simply be a good definition of the annotation

We defined above comments main use of the String type, but in fact can also be basic data types (not as packaging), enumerated types.

Notes also has something of a convention, the most common parameters should be named value, while under normal circumstances we will set a default by default parameters.

But this is not to be satisfied with our use of it, I would like to @Tablecomment only on the class, @Columannotation is only used on the property, how do? And three notes mentioned at the beginning, developers are used in general run of notes, is that we define it?

To answer these questions, we need to introduce the concept of a "meta-annotation."

3.1 yuan notes

Annotations can be modified is the meta-annotation annotations, Java has defined a number of meta-annotation, we can directly use.

3.1.1 @Target

As the name suggests the use of annotations to specify a target object parameter is ElementType []

public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}

The following is ElementType defined properties enumeration, do not set Target, apart TYPE_PARAMETER, TYPE_USE, other parts are equivalent to the configuration.

public enum ElementType {
    /** 通过ElementType.TYPE可以修饰类、接口、枚举 */
    TYPE,

    /** 通过ElementType.FIELD可以修饰类属性 */
    FIELD,

    /** 通过ElementType.METHOD可以修饰方法 */ METHOD, /** 通过ElementType.PARAMETER可以修饰参数(如构造器或者方法中的) */ PARAMETER, /** 通过ElementType.CONSTRUCTOR可以修改构造器 */ CONSTRUCTOR, /** 通过ElementType.LOCAL_VARIABLE可以修饰方法内部的局部变量 */ LOCAL_VARIABLE, /** 通过ElementType.ANNOTATION_TYPE可以修饰注解 */ ANNOTATION_TYPE, /** 通过ElementType.PACKAGE可以修饰包 */ PACKAGE, /** * 可以用在Type的声明式前 * * @since 1.8 */ TYPE_PARAMETER, /** * 可以用在所有使用Type的地方(如泛型、类型转换等) * * @since 1.8 */ TYPE_USE }

We mainly talk about ElementType.PACKAGE and ElementType.TYPE_PARAMETER and ElementType.TYPE_USE 1.8 added

ElementType.PACKAGE

@Target(ElementType.PACKAGE)
public @interface Table {
    String value() default ""; }

Meaning is used to modify the package, but when we used to modify the package has an error

We follow the prompts to create package-info.java file, need to take note here, a new by IDE -> Java Class is not created by the need to create a new File file

@Table
package annotation;
class PackageInfo { public void hello() { System.out.println("hello"); } }

ElementType.TYPE_PARAMETER和ElementType.TYPE_USE

Both say it together, because they have similarities. Are added after Java1.8

@Target(ElementType.TYPE_USE)
public @interface NoneEmpty {
    String value() default ""; }
@Target(ElementType.TYPE_PARAMETER)
public @interface NoneBlank {
    String value() default ""; }

Obviously use ElementType.TYPE_PARMETER modified comment @NoneBlank not be used when a generic compiler, only for generic class declaration, but modified by ElementType.TYPE_USE comment @NoneEmpty can.

3.1.2 @Retention

Annotations can be used to define the life cycle, the parameters for the enumeration RetentionPolicy, including the SOURCE, CLASS, RUNTIME

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /** * Returns the retention policy. * @return the retention policy */ RetentionPolicy value(); }
public enum RetentionPolicy {
    /**
     * 仅存在于源代码中,编译阶段会被丢弃,不会包含于class字节码文件中.
     */
    SOURCE,

    /**
     * 【默认策略】,在class字节码文件中存在,在类加载的时被丢弃,运行时无法获取到
     */
    CLASS,

    /** * 始终不会丢弃,可以使用反射获得该注解的信息。自定义的注解最常用的使用方式。 */ RUNTIME }

3.1.3 @Documented

It indicates whether this annotation information added to the document javadoc

3.1.4 @Inherited

The definition of the relationship between notes and subclasses, using this annotation statement out of the custom annotation, when used in a class above the subclass automatically inherits this comment, otherwise, the child will not inherit this class notes. Note that using @Inherited statement out of the notes, will only be effective when the use of the class, other invalid methods, properties, and so on.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Person { String value() default "man"; }
@Person
public class Parent { } //子类也拥有@Person注解 class Son extends Parent { }

3.2 annotation defined Summary

With @interface defined Note

A plurality of parameters can be added, with a value agreed by the core parameters, can set the default value for each parameter, parameter types include basic types, String and enumeration

Metadata annotation can be used to modify annotations, annotation comprising a plurality of element must be set @Targetand @Retention, @Retentiongenerally set RUNTIME.

Four. Annotation processing

We have already mentioned light configuration annotations, in fact, no action is required to implement the logic of the annotation want to express through the corresponding code.

After annotation defines also a class, all the notes are inherited from java.lang.annotation.Annotation, and therefore, reading notes, need to use the reflection API.

//定义的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Colum { String value() default ""; //用于表示某个属性代表的中文含义 String name() default ""; }

With annotations @Colum to modify the properties of a class

public class Person {

    @Colum(name = "姓名") private String name; @Colum(name = "性别") private String gender; @Colum(name = "年龄") private int age; @Colum(name = "住址") private String address; public String getName() {return name;} public void setName(String name) {this.name = name;} public String getGender() {return gender;} public void setGender(String gender) {this.gender = gender;} public int getAge() {return age;} public void setAge(int age) {this.age = age;} public String getAddress() {return address;} public void setAddress(String address) {this.address = address;} }

All fields read by reflection in Chinese meaning of this class, and stores the list and then print out

public static void main(String[] args) throws ClassNotFoundException { List<String> columNames = new ArrayList<>(); Class clazz = Class.forName("annotation.Person"); //获取Person类所有属性 Field[] fields = clazz.getDeclaredFields(); for (Field field : fields){ //获取该属性的Colum注解 Colum colum = field.getAnnotation(Colum.class); //或者可以先判断有无该注解 field.isAnnotationPresent(Colum.class); //将该属性通过注解配置好的中文含义取出来放到集合中 columNames.add(colum.name()); } //打印集合 columNames.forEach((columName) -> System.out.println(columName)); }

The results are as follows:

姓名
性别
年龄
住址

For example, we have some common scenarios, you need to list on the website exported into excel spreadsheet, we annotated by way of the column names configured, then you need to export read by reflection entity (whether or not you need to export, can also be configured via annotations) the value of each field, enabling export component excel.

V. summary

Just start a discussion paper to explain the basic concepts of annotations, notes the role, function and use of several meta-annotation methods, and through a simple example to explain about the process of annotation, not comprehensive, the paper explains the basic annotation by Field Api, but notes also can be modified class, constructor, method, etc., but also notes corresponding treatment, we can check their own API manuals related content, similar, there are imperfect, please criticism and hope to make progress together, thank you!

 
 
Category: the Java Advanced

A. What is Annotation

We see a lot of code, such as @ Override, @ SuppressWarnings, @ Test annotation like pattern is in the usual development process, annotations are placed class, constructors, methods, properties, before the parameter marker.

Two. Annotation role

To a class, method .. add a comment, this link is only made a mark, and the code itself will not have any impact, requiring subsequent links with, other methods require the notes given business logic processing. Just as we have made a shared positioned on the micro-channel, and at this time there is no use, only when other people are back into the shared location, distance to clear between us, to know how to get together.

Notes divided into three categories:

2.1 compiler uses to comment

Such as @ Override, @ SuppressWarnings are used by the compiler to comment, it is to tell the compiler something, without going into .class compiled files.

@Override: tell the compiler to rewrite the method to check whether the parent class;

@SuppressWarnings: tell the compiler to ignore the warnings section of the generated code;

For developers, it is used directly without further action

2.2 .class files to notes

Need to make some modifications to the annotated bytecode .class files by the tool, the tool will be set when some class loading, dynamic modification denoted by a .class file annotation, to achieve some special features, a one-time treatment is completed, does not exist in memory, are very low-level tool library, the framework will use for developers, generally not involved.

Notes 2.3 runtime read

Has been present in the JVM, the notes can be read during operation, is the most commonly used annotation, such as the Spring @ Controller, @ Service, @ Repository, @ AutoWired, Mybatis of @ Mapper, Junit of @Test, etc., these notes many tools are custom frameworks play a special role during operation notes, general developers can also customize this type of comment.

III. Definitions Annotation

@Interface we use to define a comment

/**
 * 定义一个Table注解
 */
public @interface Table {
    String value() default ""; }
/**
 * 定义一个Colum注解
 */
public @interface Colum {
    String value() default ""; String name() default ""; String dictType() default ""; }

This will simply be a good definition of the annotation

We defined above comments main use of the String type, but in fact can also be basic data types (not as packaging), enumerated types.

Notes also has something of a convention, the most common parameters should be named value, while under normal circumstances we will set a default by default parameters.

But this is not to be satisfied with our use of it, I would like to @Tablecomment only on the class, @Columannotation is only used on the property, how do? And three notes mentioned at the beginning, developers are used in general run of notes, is that we define it?

To answer these questions, we need to introduce the concept of a "meta-annotation."

3.1 yuan notes

Annotations can be modified is the meta-annotation annotations, Java has defined a number of meta-annotation, we can directly use.

3.1.1 @Target

As the name suggests the use of annotations to specify a target object parameter is ElementType []

public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}

The following is ElementType defined properties enumeration, do not set Target, apart TYPE_PARAMETER, TYPE_USE, other parts are equivalent to the configuration.

public enum ElementType {
    /** 通过ElementType.TYPE可以修饰类、接口、枚举 */
    TYPE,

    /** 通过ElementType.FIELD可以修饰类属性 */
    FIELD,

    /** 通过ElementType.METHOD可以修饰方法 */ METHOD, /** 通过ElementType.PARAMETER可以修饰参数(如构造器或者方法中的) */ PARAMETER, /** 通过ElementType.CONSTRUCTOR可以修改构造器 */ CONSTRUCTOR, /** 通过ElementType.LOCAL_VARIABLE可以修饰方法内部的局部变量 */ LOCAL_VARIABLE, /** 通过ElementType.ANNOTATION_TYPE可以修饰注解 */ ANNOTATION_TYPE, /** 通过ElementType.PACKAGE可以修饰包 */ PACKAGE, /** * 可以用在Type的声明式前 * * @since 1.8 */ TYPE_PARAMETER, /** * 可以用在所有使用Type的地方(如泛型、类型转换等) * * @since 1.8 */ TYPE_USE }

We mainly talk about ElementType.PACKAGE and ElementType.TYPE_PARAMETER and ElementType.TYPE_USE 1.8 added

ElementType.PACKAGE

@Target(ElementType.PACKAGE)
public @interface Table {
    String value() default ""; }

Meaning is used to modify the package, but when we used to modify the package has an error

We follow the prompts to create package-info.java file, need to take note here, a new by IDE -> Java Class is not created by the need to create a new File file

@Table
package annotation;
class PackageInfo { public void hello() { System.out.println("hello"); } }

ElementType.TYPE_PARAMETER和ElementType.TYPE_USE

Both say it together, because they have similarities. Are added after Java1.8

@Target(ElementType.TYPE_USE)
public @interface NoneEmpty {
    String value() default ""; }
@Target(ElementType.TYPE_PARAMETER)
public @interface NoneBlank {
    String value() default ""; }

Obviously use ElementType.TYPE_PARMETER modified comment @NoneBlank not be used when a generic compiler, only for generic class declaration, but modified by ElementType.TYPE_USE comment @NoneEmpty can.

3.1.2 @Retention

Annotations can be used to define the life cycle, the parameters for the enumeration RetentionPolicy, including the SOURCE, CLASS, RUNTIME

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /** * Returns the retention policy. * @return the retention policy */ RetentionPolicy value(); }
public enum RetentionPolicy {
    /**
     * 仅存在于源代码中,编译阶段会被丢弃,不会包含于class字节码文件中.
     */
    SOURCE,

    /**
     * 【默认策略】,在class字节码文件中存在,在类加载的时被丢弃,运行时无法获取到
     */
    CLASS,

    /** * 始终不会丢弃,可以使用反射获得该注解的信息。自定义的注解最常用的使用方式。 */ RUNTIME }

3.1.3 @Documented

It indicates whether this annotation information added to the document javadoc

3.1.4 @Inherited

The definition of the relationship between notes and subclasses, using this annotation statement out of the custom annotation, when used in a class above the subclass automatically inherits this comment, otherwise, the child will not inherit this class notes. Note that using @Inherited statement out of the notes, will only be effective when the use of the class, other invalid methods, properties, and so on.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Person { String value() default "man"; }
@Person
public class Parent { } //子类也拥有@Person注解 class Son extends Parent { }

3.2 annotation defined Summary

With @interface defined Note

A plurality of parameters can be added, with a value agreed by the core parameters, can set the default value for each parameter, parameter types include basic types, String and enumeration

Metadata annotation can be used to modify annotations, annotation comprising a plurality of element must be set @Targetand @Retention, @Retentiongenerally set RUNTIME.

Four. Annotation processing

We have already mentioned light configuration annotations, in fact, no action is required to implement the logic of the annotation want to express through the corresponding code.

After annotation defines also a class, all the notes are inherited from java.lang.annotation.Annotation, and therefore, reading notes, need to use the reflection API.

//定义的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Colum { String value() default ""; //用于表示某个属性代表的中文含义 String name() default ""; }

With annotations @Colum to modify the properties of a class

public class Person {

    @Colum(name = "姓名") private String name; @Colum(name = "性别") private String gender; @Colum(name = "年龄") private int age; @Colum(name = "住址") private String address; public String getName() {return name;} public void setName(String name) {this.name = name;} public String getGender() {return gender;} public void setGender(String gender) {this.gender = gender;} public int getAge() {return age;} public void setAge(int age) {this.age = age;} public String getAddress() {return address;} public void setAddress(String address) {this.address = address;} }

All fields read by reflection in Chinese meaning of this class, and stores the list and then print out

public static void main(String[] args) throws ClassNotFoundException { List<String> columNames = new ArrayList<>(); Class clazz = Class.forName("annotation.Person"); //获取Person类所有属性 Field[] fields = clazz.getDeclaredFields(); for (Field field : fields){ //获取该属性的Colum注解 Colum colum = field.getAnnotation(Colum.class); //或者可以先判断有无该注解 field.isAnnotationPresent(Colum.class); //将该属性通过注解配置好的中文含义取出来放到集合中 columNames.add(colum.name()); } //打印集合 columNames.forEach((columName) -> System.out.println(columName)); }

The results are as follows:

姓名
性别
年龄
住址

For example, we have some common scenarios, you need to list on the website exported into excel spreadsheet, we annotated by way of the column names configured, then you need to export read by reflection entity (whether or not you need to export, can also be configured via annotations) the value of each field, enabling export component excel.

V. summary

Just start a discussion paper to explain the basic concepts of annotations, notes the role, function and use of several meta-annotation methods, and through a simple example to explain about the process of annotation, not comprehensive, the paper explains the basic annotation by Field Api, but notes also can be modified class, constructor, method, etc., but also notes corresponding treatment, we can check their own API manuals related content, similar, there are imperfect, please criticism and hope to make progress together, thank you!

Guess you like

Origin www.cnblogs.com/xichji/p/11627085.html