Notes Getting Started (a)

This blog to explain divided into the following issues

  1. Notes related knowledge
  2. Examples of annotation-based run-time analytic description

As for the comment about compile time, the time will be next blog with examples explain now and I'm learning them

Notes related knowledge

Notes mentioned, most people should not default, see in our program @ Override, @ Deprected, @ SupressWarnings and so on, these are the notes, but the system itself is a good package, and we usually go less depth understanding of how to achieve?

1) What are annotations (Annotation):

Annotation (annotation) is Java provides an association with any information and any metadata (metadata) ways and means of a meta-program elements. Annotion (Notes) is an interface, the program can obtain the specified target Annotion program element through reflection, and then acquires metadata annotations by Annotion inside the object.

2) annotation Category:

According to the number of annotation parameters, we can annotate divided into three categories:

  1. Mark notes: Annotation is not a member of the defined type is called a marker annotation. Annotation of this type using only their presence or absence to provide information to us. For example @Override back annotation system;
  2. Single-value notes
  3. Full comment 

According to notes using the methods and uses, we can Annotation divided into three categories:

  1. JDK built-in system Notes
  2. Yuan notes
  3. Custom annotation

3) meta-annotation:

Meta-annotation role is responsible for other annotation notes. Java5.0 standard defines four meta-annotation type, which are used to provide other types of annotation specified. Java5.0 defined meta-annotation:

  1. @Target,
  2. @Retention,
  3. @Documented,
  4. @Inherited

4) meta-annotation parsing instructions

  • Whether @Documented saved to the Javadoc documentation

  • @Retention retention time, optional value

    The SOURCE (when the source), the CLASS (compile-time), RUNTIME (running), the default is CLASS, SOURCE mostly Mark Annotation, such Annotation mostly used to verify, for example Override, SuppressWarnings

  • @Target program elements which can be used, such as TYPE, METHOD, CONSTRUCTOR, FIELD, PARAMETER other modifications, may be modified is not marked indicates that all the

    ANONOTATION_TYPE (annotation type declaration),
    PACKAGE of (packet)
    the TYPE (class, and interface including enum, annotation types)
    the METHOD (Method)
    CONSTRUCTOR (constructor)
    FIFLD (member variables)
    paramater (parameter)
    LOCAL_VARIABLE (local variables)

  • Whether @Inherited can be inherited, the default is false

5) What is metadata (metadata):

Metadata translated from the word metadata, is "data about data" means.
 
 Function There are many meta data, for example: you may automatically generate documents used Javadoc comments. This is a meta data capabilities. Overall, the metadata can be used to create documents, dependency tracking code, compile-time checking format, instead of the existing configuration files. If you want to classify the role of metadata, there is no clear definition, but we can play a role in it, it can be broadly divided into three categories:

  1. Documenting: metadata generated by the document identification code
  2. Code analysis: analyzed by the code of the identification code metadata
  3. Compile check: through metadata identification code so that the compiler can achieve the basic compiler checks

Other knowledge is not being introduced, personally I feel that too much at once introduce the concept difficult to digest. Let us together with examples to use it.


Here we look at how we can write a custom annotation-based example of the compile-time

Custom annotation can be broadly divided into the following three steps:

  1. Customizing a comment
  2. Use our comments in other classes
  3. Our analytical notes at run time

Parsing operation flow chart

1) First, we we look at how we define a custom annotations

These types of classes and they support can be found in java.lang.annotation package.

/* 
 * 定义注解 MethodInfo 
 * 为方便测试:注解目标为类 方法,属性及构造方法 
 * 注解中含有三个元素 id ,name和 gid; 
 * id 元素 有默认值 0
 */ 

@Documented 
@Target({ElementType.TYPE,ElementType.METHOD,
    ElementType.FIELD,ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MethodInfo {
    String name() default "xujunTest";
    int id() default 0;
    Class<Long> gid();
}

Analytical description

  • (1). @Interface by definition, annotation name is the name of a custom annotations, notes here called MethodInfo
  • (2) the name of the annotation configuration parameter called annotation category, and:

    a. All method is not a method thereof, no modifier has no parameters, only the actual public & abstract modifier, the default is public, allowed Throws

    b. Method return value must be either primitive type, String, Class, annotation, enumeration or their one-dimensional array

    c. If only one default property, it can be directly used value () function. A property are not expressed as Mark Annotation The Annotation
  • (3) indicates the default value can be added default, such as

String name() default "xujunTest";

2) Then we look at how we can use our custom annotations

/**
 * 这个类专门用来测试注解使用
 * @author xujun
 */
 //类成员注解
@MethodInfo (name="type",gid=Long.class) 
public class UserAnnotation {
    //类成员注解
    @TestA(name="param",id=1,gid=Long.class) 
    private Integer age;
    
    //构造方法注解
    @TestA (name="construct",id=2,gid=Long.class)
    public UserAnnotation(){
        
    }
    
    //类方法注解
    @TestA(name="public method",id=3,gid=Long.class)      
    public void a(){
        Map<String,String> m = new HashMap<String,String>(0);
    }
    
    //类方法注解
    @TestA(name="protected method",id=4,gid=Long.class) 
    protected void b(){
        Map<String,String> m = new HashMap<String,String>(0);
    }
    
    //类方法注解
    @TestA(name="private method",id=5,gid=Long.class) 
    private void c(){
        Map<String,String> m = new HashMap<String,String>(0);
    }
    
    public void b(Integer a){ 
        
    }
}

3) Finally, we look together how we resolve our Annotation annotation at runtime

Annotation resolve runtime

(1) Annotation means to RUNTIME runtime @Retention the Annotation, it can be used to call the following API manually parse

method.getAnnotation(AnnotationName.class);
method.getAnnotations();
method.isAnnotationPresent(AnnotationName.class);

Other such @Target Field, Class method analogous

  • getAnnotation (AnnotationName.class) indicates that the information obtained Annotation of a Target, Target can be modified as a plurality Annotation
/*
* 根据注解类型返回方法的指定类型注解
*/
MethodInfo annotation = (MethodInfo) constructor
                     .getAnnotation(MethodInfo.class);
  • getAnnotations () indicates that all Target obtained Annotation
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
    MethodInfo methodInfo = (MethodInfo) annotation
}
  • isAnnotationPresent (AnnotationName.class) indicates whether the Target is a modified Annotation
/*
* 判断构造方法中是否有指定注解类型的注解
*/
boolean hasAnnotation = constructor
.isAnnotationPresent(MethodInfo.class);
if (hasAnnotation) {
    /*
    * 根据注解类型返回方法的指定类型注解
    */
    MethodInfo annotation = (MethodInfo) constructor
    .getAnnotation(MethodInfo.class);
}

Test code

public class ParseAnnotation {
    
    static String className="com.xujun.animation.test.UserAnnotation";
    /**
     * 简单打印出UserAnnotation 类中所使用到的类注解 该方法只打印了 Type 类型的注解
     * 
     * @throws ClassNotFoundException
     */
    public static void parseTypeAnnotation() throws ClassNotFoundException {
        Class clazz = Class.forName(className);

        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            MethodInfo testA = (MethodInfo) annotation;
            System.out.println("id= \"" + testA.id() + "\"; name= \""
                    + testA.name() + "\"; gid = " + testA.gid());
        }
    }

    /**
     * 简单打印出UserAnnotation 类中所使用到的方法注解 该方法只打印了 Method 类型的注解
     * 
     * @throws ClassNotFoundException
     */
    public static void parseMethodAnnotation() {
        Method[] methods = UserAnnotation.class.getDeclaredMethods();
        for (Method method : methods) {
            /*
             * 判断方法中是否有指定注解类型的注解
             */
            boolean hasAnnotation = method.isAnnotationPresent(MethodInfo.class);
            if (hasAnnotation) {
                /*
                 * 根据注解类型返回方法的指定类型注解
                 */
                MethodInfo annotation = method.getAnnotation(MethodInfo.class);
                System.out.println("method = " + method.getName() + " ; id = "
                        + annotation.id() + " ; description = "
                        + annotation.name() + "; gid= " + annotation.gid());
            }
        }
    }

    /**
     * 简单打印出UserAnnotation 类中所使用到的方法注解 该方法只打印了 Method 类型的注解
     * 
     * @throws ClassNotFoundException
     */
    public static void parseConstructAnnotation() {
        Constructor[] constructors = UserAnnotation.class.getConstructors();
        for (Constructor constructor : constructors) {
            /*
             * 判断构造方法中是否有指定注解类型的注解
             */
            boolean hasAnnotation = constructor
                    .isAnnotationPresent(MethodInfo.class);
            if (hasAnnotation) {
                /*
                 * 根据注解类型返回方法的指定类型注解
                 */
                MethodInfo annotation = (MethodInfo) constructor
                        .getAnnotation(MethodInfo.class);
                System.out.println("constructor = " + constructor.getName()
                        + " ; id = " + annotation.id() + " ; description = "
                        + annotation.name() + "; gid= " + annotation.gid());
            }
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        parseTypeAnnotation();
        parseMethodAnnotation();
        parseConstructAnnotation();
    }
}

Run the above test procedures, you will be able to see the following output

id= "0"; name= "type"; gid = class java.lang.Long
method = c ; id = 5 ; description = private method; gid= class java.lang.Long
method = b ; id = 4 ; description = protected method; gid= class java.lang.Long
method = a ; id = 3 ; description = public method; gid= class java.lang.Long
constructor = com.xujun.animationdemo.UserAnnotation ; id = 2 ; description = construct; gid= class java.lang.Long


Reproduced, please indicate the original blog address:

Source Download:

Related blog Recommended

java Type Detailed

Detailed java reflection mechanism

Notes Getting Started (a)

Android custom compile time Note 1 - Simple example

Notes compiled with the Android - Detailed grammar

Take you read ButterKnife source

Sweep swept away, I welcome the attention of the public micro-channel number stormjun94 (Xu code word) , is currently a programmer, Android developers not only to share knowledge, but also to share technical people grew up, including personal summary, experience in the workplace, interview experience and so on, you want to make less go a little detour.

Guess you like

Origin www.cnblogs.com/gdutxiaoxu/p/11645751.html