springMVC custom annotation (@ Retention @ Target) Comments

Custom annotation:

  @Interface use custom annotations automatically inherited java.lang.annotation.Annotation interfaces, complete other details automatically by the compiler. When defining notes, annotations can not inherit or other interfaces. @interface used to declare an annotation, each of which method is actually declares a configuration parameter. Name of the method is the name of the parameter, return type is the type parameter (return value type can only be a basic type, Class, String, enum). You can declare the default value of the parameter by default.

Format defined Note:
  public @interface annotation definition body name} {

  Notes parameter can support data types:

    1. All elementary data types (int, a float, Boolean, byte, Double, char, Long, Short)
    2.String type
    3.Class type
    4.enum type
    5.Annotation type
    6. The above array of all types of

  Annotation type inside the parameters of how the set:
  first, only with public or default (default) access to these two modifications, such as, String value (); here, the default method is set defaul type;.   
  Second, the parameters members using essentially the only type byte, short, char, int, long, float, double, boolean eight basic data types and String, Enum, Class, annotations and other data types, and some of this type of array, for example, String value () ; here it is a member of parameters String;  
  third, if only one member of parameters, it is best to set the parameter name "value", after adding parentheses Example: the following example FruitName comment on only one parameter members.

  Simple custom annotations and notes using an example:
  

package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 水果名称注解
 * @author peida
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitName {
    String value() default "";
}
package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 水果颜色注解
 * @author peida
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitColor {
    /**
     * 颜色枚举
     * @author peida
     *
     */
    public enum Color{ BULE,RED,GREEN};
    
    /**
     * 颜色属性
     * @return
     */
    Color fruitColor() default Color.GREEN;

}
package annotation;

import annotation.FruitColor.Color;

public class Apple {
    
    @FruitName("Apple")
    private String appleName;
    
    @FruitColor(fruitColor=Color.RED)
    private String appleColor;
    
    
    
    
    public void setAppleColor(String appleColor) {
        this.appleColor = appleColor;
    }
    public String getAppleColor() {
        return appleColor;
    }
    
    
    public void setAppleName(String appleName) {
        this.appleName = appleName;
    }
    public String getAppleName() {
        return appleName;
    }
    
    public void displayName(){
        System.out.println("水果的名字是:苹果");
    }
}

Meta-annotation (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 element annotation definition:
 1. the Target @ , used to describe the use of annotations (the method, constructor, member variables enumerated value)
   

Value (ElementType) are:

1.CONSTRUCTOR: constructor is used to describe
2.FIELD: for describing fields
3.LOCAL_VARIABLE: local variables used to describe
4.METHOD: a method for describing
5.PACKAGE: Package for describing
6.PARAMETER: parameter used to describe the
7.TYPE: used to describe the class, interface (including type of annotation), or an enum declaration

 
 @ Retention 2. , expressed the need to save the annotation information on what level, is used to describe the life cycle of notes

Value (RetentionPoicy) are:

1.SOURCE: active (i.e., the source file remains) in the source file
2.CLASS: active (i.e., class reserved) in the class file
3.RUNTIME: active (i.e., retention operation) at runtime (attribute value is RUTIME, so the processor can be reflected by the annotation, the acquired attribute values of the annotation)

 3. @ Documented used to describe other types of annotation program should be as members of the public API is labeled, it can be, for example, such tools documentation javadoc
 
4. @ Inherited @Inherited element annotation is a marker annotation, @ Inherited forth a certain type of indexed is inherited. If using a modified @Inherited annotation type is used for a class, then this annotation is used in a subclass of this class.

Use annotations:

The first step: create a new annotation, named: MyAnnotation.java.

package com.dragon.test.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by gmq on 2015/9/10.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{

    String hello () default "hello";
    String world();
}

The second step: the establishment of a MyTest.java to use the above annotation.

package com.dragon.test.annotation;

/**
 * Created by gmq on 2015/9/10.
 */
public class MyTest
{

    @MyAnnotation(hello = "Hello,Beijing",world = "Hello,world")
    public void output() {
        System.out.println("method output is running ");
    }
}

The third step: using reflection to call the contents of notes

package com.dragon.test.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 用反射机制来调用注解中的内容
 * Created by gmq on 2015/9/10.
 */
public class MyReflection
{
    public static void main(String[] args) throws Exception
    {
        // 获得要调用的类
        Class<MyTest> myTestClass = MyTest.class;
        // 获得要调用的方法,output是要调用的方法名字,new Class[]{}为所需要的参数。空则不是这种
        Method method = myTestClass.getMethod("output", new Class[]{});
        // 是否有类型为MyAnnotation的注解
        if (method.isAnnotationPresent(MyAnnotation.class))
        {
            // 获得注解
            MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
            // 调用注解的内容
            System.out.println(annotation.hello());
            System.out.println(annotation.world());
        }
        System.out.println("----------------------------------");
        // 获得所有注解。必须是runtime类型的
        Annotation[] annotations = method.getAnnotations();
        for (Annotation annotation : annotations)
        {
            // 遍历所有注解的名字
            System.out.println(annotation.annotationType().getName());
        }
    }
}

Output:

Hello,Beijing
Hello,world

Reference: https: //www.cnblogs.com/gmq-sh/p/4798194.html


The concept notes

Annotation (Annotation), also known as metadata (Metadata), is a new feature of Java5, JDK5 introduced Metadata very easy to be able to call Annotations. Notes and classes, interfaces, enumerations at the same level, and can be applied to packages, types, constructors, methods, member variables, parameters, local variables declaration, to comment on these elements will be described.

Annotation syntax defined form

(1) to define the keyword @interface
(2) notes contain members who are in the form of non-parametric methods are declared. Its method name and return value defines the name and type of the member.
(3) members are assigned by @Annotation (name = value) form.
Information (4) notes need to indicate annotations life cycle, comment modification goals, such information is achieved through metadata annotation.

Java.lang.annotation to Target annotation defined to illustrate:

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.ANNOTATION_TYPE } )
public @interface Target {
    ElementType[] value();
}

Source as follows:
First: element annotation @Retention, the value member is RetentionPolicy.RUNTIME.
Second: @Target element annotation, is a member of an array value, assigning a {} form, is ElementType.ANNOTATION_TYPE
third: member name value, type of the ElementType []
Further, it is noted that, if a member name value, in the assignment process can be abbreviated. If the member is an array type, but only assign one element, it can be abbreviated. As described above shorthand form:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    ElementType[] value();
}

Classification annotations

There are two sub-classification annotations law:

The first is a points system

1, the basic built-in annotations, refers to the Java comes with several Annotation, such as @ Override, Deprecated, @ SuppressWarnings and so on;

2, metadata annotations (meta-annotation), responsible for annotation refers to notes other annotations, JDK 1.5 and later versions of the standard defines four types of metadata annotation, as follows:

@Target
@Retention
@Documented
@Inherited
. 3, custom annotations, annotation can be customized according to the needs, the need to use custom annotations above meta-annotation

Reference: https: //blog.csdn.net/github_35180164/article/details/52107204


Java meta-annotation rules @Retention

@Retention java is among a meta-annotation, the yuan notes are often used to test the software

1, for the way:
@Retention(RetentionPolicy.RUNTIME)
    @interface Task{.......}

It shows the parameters RetentionPolicy.RUNTIME, @ Task annotation is visible when the program runs
RetentionPolicy enumerated types as well as SOURCE, CLASS specify annotations are visible to that level, however, we usually use RUNTIME , because this is annotations can be read at runtime, making it easy to test software

2, then we must first introduce introspection and reflection java program, after discussing specific examples of usage @Retention

In the java virtual machine running the JVM, the class would be loaded, this time, each class generates an object data type of a Class (Class class java.lang.Class), the object is "class corresponding to the running when the object "by the run-time object, you can get a lot of information corresponding to the class, that is, run-time object is actually a map corresponding to the class , and this introspection java reflection mechanism

3. Next, we discuss the use of this Class runtime object

① --getClass object reference when acquiring the data type of the corresponding class Class run ()

     public class Point{.....} //声明一个类
     Point pt = new Point(); //创建对应类的实例对象
     Class cls = pt.getClass() ;    //则cls 就指向了Point类的运行时对象

② runtime objects cls member functions

<1>public String  getName()
     返回对应类的类名
     
<2>public boolean isAnnotationPresent(注解名.class)
     判定指定的"注解"是否在运行时注解了 cls 的对应类
     
     <3>public boolean isAnnotation();
     判定cls 是否在运行时被任何注解 注解过
     
<4>public A getAnnotation(注解名.class)
     A 指的是一个注解的类型,具体用法如下:
     @Retention(RetentionPolicy.RUNTIME) //指定@Task运行时可见
     @interface Task{String descirption(); }
     
     @Task(descroption="NoFinished")   //为computer作注
     class Computer{.....} 
     则  Computer my = new Computer() ;
         Class cls = my.getClass() ;
         Task tk = (Task) cls.getAnnotation(Task.class);
         //这时 tk 就指向了标注Computer的注解@Task
         tk.description(); //调用@Task中的description(),输出"NoFinishing"
         
 <5> public Method[] getMethods()
        返回由对应类中的所有的方法形成的Method数组,每个Method对象都唯一对应
        一个对应类中的方法,通过Method[i]就可以获得对应方法的信息
        (Method类在java.lang.reflect.Method中)
       
        这个Method类也有很多成员方法,用来获取对应的方法的信息

        如也有:
       public boolean isAnnotationPresent(注解名.class)
       判定对应的方法是否被指定的注所注解
       public A getAnnotation(注解名.class)
       用法和上面的讲述的一样,之不过创建的注解型的引用变量指向的是 "标记对应方法的注解"

The above will be able to play a role if all the members of the method is only visible in the comment runtime, it becomes useful @Retention

Reference: https: //www.cnblogs.com/PengLee/p/3902836.html

Guess you like

Origin www.cnblogs.com/both-eyes/p/11078129.html