Custom annotation [fine]

Custom annotation

I. Introduction

In the process of developing a variety of xml configuration files cause complicated configuration steps, code logic is not intuitive and other issues have been gradually replacing notes, are everywhere now encoding various notes, how to customize a note that use in the project?

Second, the custom annotation need to know

& Custom annotation types: Define a new annotation class uses @interface keyword, define a class with the same level.

& Custom annotation class inheritance: custom annotation class automatically inherits java.lang.annotation.Annotation Interface 

& Custom annotation class member variables: the custom annotation member variables defined in the class, stated in a non-parametric method form. The name of the method is the variable name, method return value type is the variable type. (Also known as member variables configuration parameters)

    * For example: String name () {} -> name is the variable name, String is the type of variable.

& Type member variable: the eight basic data types, String type, Class type, enum type, Annotation type, all of the above types of arrays

& Custom annotation Default: When you create class notes, if you need to create the initial value. You can create a default initial value using a variable, the variable name commonly used value

    * 例如: boolean value() default true

& If a comment contains configuration parameters defined, you must specify parameter values ​​when in use, unless it has a default value. The format is "parameter name = parameter value", if only one member of the parameter, and name value, you can omit "value ="

Third, custom annotation

Introduction to use custom annotations above, notes to create a deeper understanding of the content above.

  • Creating notes
/**
 * 使用 @interface 关键字 定义一个注解
 * 自定义注解默认自动继承了java.lang.annotation.Annotation接口
 */

public @interface MyAnnotation {

}
  •  Create notes no initial value parameter configuration
public @interface MyAnnotation {
    // 定义注解成员变量,value就是变量名称,String就是变量类型。成员变量又叫参数配置
    // 没有指定初始值的参数配置 
    String value();
}

    Use annotations no initial value, you need to assign a parameter.

// 使用注解,给参数赋值
@MyAnnotation(value = "王刚")
public class AnnotationTest {
    private static String name="张伟";

    public static void main(String[] args) {
        System.out.println(name);
    }

}
  • Creating annotation parameters have been initialized values
public @interface MyAnnotation {
    /**
     * 1.使用 default 关键字 初始化 参数配置 值
     * 2.如果只有一个参数配置,建议参数配置名称使用value
     * @return
     */
    String value()  default "张国强";
}

     Notes initial configuration parameters at the time of use may not assign

// 初始化参数配置,使用注解时可以不用赋值
@MyAnnotation
public class AnnotationTest {
    private static String name="张伟";

    public static void main(String[] args) {
        System.out.println(name);
    }

}

Fourth, the yuan notes

Yuan notes : Pertaining to other Annotion of Annotion is a meta-annotation meta-annotation

Yuan notes four types : Retention, Target, Documented, Inherited

 @Retention : Specifies the Annotation life cycle. @Rentention RetentionPolicy contains a member variable of type, specify a value for the value member variables must use @Rentention

    * RetentionPolicy.SOURCE: effective (ie, the source file remains), the compiler discards the comments of this strategy in the source file.

    * RetentionPolicy.CLASS: effective (ie class reserved) in the class file when you run a Java program, JVM does not retain notes. This is the default value

    * RetentionPolicy.RUNTIME: effective (ie reserved runtime) At runtime, when Dangdang line to run Java programs, JVM will retain comments. Note that the program may be obtained by reflection.

 @Target : defining a custom annotation program elements which can be used to code. @Target also contains a member variable named value.

    * TYPE: define custom annotations based on the application

    * CONSTRUCTOR: define custom annotations Application Builder

    * FIELD: defining a custom attribute field annotation application

    * METHOD: define custom annotations Application method

    * PARAMETER: define custom annotations in the form of parameters used in the method

    * LOCAL_VARIABLE: define custom annotations in the application of local variables

    * ANNOTATION_TYPE: define custom annotations in the annotation type of application

    * PACKAGE: defining a custom Application Package annotations

@Documented : Notes on a custom application class is generated JavaDoc documentation. By default, Javadoc is not included in the annotation, the annotation must be defined as set Documented Retention RUNTIME value .

@ Inherited : is it modified Annotation will have inherited. If a class is @Inherited modified using the Annotation, then it will automatically have the subclass comment.

Fifth, the use of meta-annotation

  •  @Retention element annotation: Annotation specified life cycle, life cycle in the above range of values ​​to metadata annotation described.
//定义自定义注解的生命周期
@Retention(RetentionPolicy.SOURCE)

public @interface MyAnnotation {
    /**
     * 1.使用 default 关键字 初始化 参数配置 值
     * 2.如果只有一个参数配置,建议参数配置名称使用value
     * @return
     */
    String value()  default "张国强";
}
  • @Target: defining a custom annotation program elements which can be used to code. @Target also contains a member variable named value.
/**
 * 用于指定被修饰的 Annotation 能用于修饰哪些程序元素
 */
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
@Retention(RetentionPolicy.SOURCE)
public @interface MyAnnotation {
    /**
     * 1.使用 default 关键字 初始化 参数配置 值
     * 2.如果只有一个参数配置,建议参数配置名称使用value
     * @return
     */
    String value()  default "张国强";
}

    Target only definition METHOD, then this can only comment on the methods used.

//定义注解只能用在方法上
@Target({METHOD})

@Retention(RetentionPolicy.SOURCE)
public @interface MyAnnotation {
    /**
     * 1.使用 default 关键字 初始化 参数配置 值
     * 2.如果只有一个参数配置,建议参数配置名称使用value
     * @return
     */
    String value()  default "张国强";
}

    Test Target range

  •  @Documented: Notes on a custom application class is generated JavaDoc documentation. By default, Javadoc is not included in the annotation, the annotation must be defined as set Documented Retention RUNTIME value .
@Documented
public @interface MyAnnotation {
    /**
     * 1.使用 default 关键字 初始化 参数配置 值
     * 2.如果只有一个参数配置,建议参数配置名称使用value
     * @return
     */
    String value()  default "张国强";
}

        TestApp class is used @Documented notes, annotations name after generating JavaDoc documentation, the class will now be used in the document.

class TestApp{
    /**
     * 该方法为测试方法
     */
    @MyAnnotation
    public static void test() {
        System.out.println("测试方法");
    }
}
  • @Inherited: is it modified Annotation will have inherited. If a class is @Inherited modified using the Annotation, then it will automatically have the subclass comment.
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface MyAnnotation {
    /**
     * 1.使用 default 关键字 初始化 参数配置 值
     * 2.如果只有一个参数配置,建议参数配置名称使用value
     * @return
     */
    String value()  default "张国强";
}

         Define a subclass inherits the parent class, just add a comment to be @Inherited modified on the parent class, subclass does not add annotations.

/**
 * 定义Tests为父类,TestApp继承父类。在父类上添加一个被 @Inherited 修饰的注解 @MyAnnotation
 */
@MyAnnotation
class Tests{
    public static void test() {
        System.out.println("父类");
    }
}

class TestApp extends Tests{
    /**
     * 该方法为测试方法
     */
    public static void test() {
        System.out.println("子类");
    }
}

          Test categories: annotation information to obtain subclass through reflection, explanation subclass inherits the parent class notes.

public class AnnotationTest {
    
    public static void main(String[] args) {
        
        //反射获取子类的字节码文件。
        Class clazz = TestApp.class;
        //获取子类的注解信息
        Annotation[] annotations = clazz.getAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            System.out.println(annotations[i]);
        }

    }

}

        Test Results

@day.annotation.MyAnnotation(value=张国强)

Six, Java8 notes new features

  • @Repeatable: annotations may be repeated, reuse the same annotation on a class.

Repeat Usage notes:

Need to define two annotations, annotation name is assumed as A and B

    ①, A comment on the statement @Repeatable, members of the value of B Notes Name: B.class

    ②, B type annotation parameters must be an array of type A: A [] value ();

    ②, annotation metadata annotation A and B of annotation metadata annotation information must be the same.

  • Examples of repeated notes

        A comment

//重复注解
@Repeatable(B.class)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})

public @interface A {
    String value() default "Hello My is A";
}

        B Notes

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface B {
    A[] value();
}

     Test category

public class App {
    //重复使用注解
    @A("My is name A")
    @A("My is name B")

    public void test() {
        System.out.println("测试类");
    }
}
  •  @Target notes extended parameters

java8 added @Target two types of parameters in the parameter so that annotations can be used anywhere.

TYPE_PARAMETER: indicates that the notes can be written on the declaration type variables (such as: generic declaration)

TYPE_USE: indicates that the notes can be written in any type of use statement

         Notes @Target annotation instances

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR,LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})

public @interface A {
    String value() default "Hello My is A";
}

        Test category

// TYPE_PARAMETER类型将注解使用在泛型上
public class App<@A T> {
    /**
     * TYPE_USE 将注解使用在 异常、集合、类型转换
     */
    public void test(T t) throws @A RuntimeException{
        List<@A String> list = new ArrayList<>();

        int num = (@A int) 10L;
        System.out.println("测试类");
    }
}

 

Published 316 original articles · won praise 117 · views 420 000 +

Guess you like

Origin blog.csdn.net/m0_38039437/article/details/104900963