java-- custom annotations (annotations take effect at runtime)

Turn: https: //www.cnblogs.com/acm-bingzi/p/javaAnnotation.html

What is a comment?

Annontation is a new feature introduced Java5 start, the Chinese name called annotations . It provides a mechanism similar security annotations for any information or metadata (Metadata) the program elements (classes, methods, member variables, etc.) associated. For the program element (classes, methods, member variables) plus more intuitive and clear instructions, these instructions are independent of the information service logic programs, and for the specified tool or framework. Annontation like one kind of modifier, as applied to the package, type declaration statements, constructors, methods, member variables, parameters and local variables.
  Java annotations are added to the code of some meta information for some of the tools in the compilation, parsing and using runtime, play instructions, configuration functions. Notes not and can not affect the actual logic of the code, only play a supplementary role. Java.lang.annotation contained in the package.

Notes usefulness:

1, generate documentation. This is the most common, is the first to provide the annotations java. Commonly used @param @return the like
2, the tracking code dependencies, alternative implementations profile function. Dagger 2 such dependency injection, java development in the future, a large number of annotations configuration, having great use;
3, format checked at compile time. On the front as @override method, this method if you are not covered by the superclass method, the compiler can check out time.

Notes principle:

Notes is essentially a special interface Annotation inherited, the specific implementation class is generated by the Java run-time dynamic proxy class. And when we get notes through reflection, returns generated Java run-time dynamic proxy object $ Proxy1. Custom annotation (Interface) method call through a proxy object, will end up calling the invoke method AnnotationInvocationHandler. This method corresponding to an index value from this memberValues ​​Map. The source memberValues ​​is Java constant pool.

Yuan notes:

java.lang.annotation offers four yuan notes, special notes to other notes (in custom annotation when the need to use meta-annotation):
   @Documented - whether notes will be included in the JavaDoc
   @Retention - when to use the annotation
   @Target - what annotations are used
   @Inherited - whether to allow the subclass inherits the comment

  . 1) @ Retention - the definition of the annotation lifecycle
  ● RetentionPolicy.SOURCE: discarded at compile time. These annotations at the end of the compiler will no longer have any meaning, they do not write byte code. @Override, @SuppressWarnings belong to such comments.
  ● RetentionPolicy.CLASS: class loading when discarded. Useful bytecode files. NOTE Using this way by default
  ● RetentionPolicy.RUNTIME: are never discarded run also keep the notes, so you can use reflection to read the annotation information. Annotations our custom commonly used in this way.

  2.) Target - indicates that the annotations are used where. The default value is any element, indicating that the annotation is used somewhere. Available parameters include ElementType
  ● ElementType.CONSTRUCTOR: constructor is used to describe
  ● ElementType.FIELD: member variables, objects, properties (including enum example)
  ● ElementType.LOCAL_VARIABLE: local variables used to describe
  ● ElementType.METHOD: a method for describing
  ● ElementType.PACKAGE: package for describing
  ● ElementType.PARAMETER: parameters used to describe
  ● ElementType.TYPE: for describing class, interface (including type of annotation), or an enum declaration

 3) @ Documented -. A simple Annotations mark notes, annotations indicating whether the information added to the java documentation.

 . 4) @ Inherited - define the relationship between the notes and subclass
     @Inherited meta-annotation is a marker annotation, @ Inherited describes 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.

Custom annotation:

Since some rules written custom annotation class:
  1. Annotation type is defined as @interface, all Annotation will automatically inherit java.lang.Annotation this interface, and can not go to inherit another class or interface.
  2. Parameter members only can be public or default (default) both access modify
  3 parameters members can only use basic types 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.
  4. for information annotated class methods and fields, must be acquired by the object annotation Java reflection technology, because there is no other way except that you obtain annotation object
  5 annotations can also define members ,, no comment on nothing but such use
PS: custom annotation need to use meta-annotation

Custom annotation demo:

Fruits Name Note:

 1 import java.lang.annotation.Documented;
 2 import java.lang.annotation.Retention;
 3 import java.lang.annotation.Target;
 4 import static java.lang.annotation.ElementType.FIELD;
 5 import static java.lang.annotation.RetentionPolicy.RUNTIME;
 6 
 7 /**
 8  * 水果名称注解
 9  */
10 @Target(FIELD)
11 @Retention(RUNTIME)
12 @Documented
13 public @interface FruitName {
14     String value() default "";
15 }

Fruit color Note:

1 import java.lang.annotation.Documented;
 2 import java.lang.annotation.Retention;
 3 import java.lang.annotation.Target;
 4 import static java.lang.annotation.ElementType.FIELD;
 5 import static java.lang.annotation.RetentionPolicy.RUNTIME;
 6 
 7 /**
 8  * 水果颜色注解
 9  */
10 @Target(FIELD)
11 @Retention(RUNTIME)
12 @Documented
13 public @interface FruitColor {
14     /**
15 * color enumeration 
16       * / 
. 17      public  enum Color {BLUE, RED, GREEN};
 18 is      
. 19      / ** 
20 is color attribute * 
21 is       * / 
22 is fruitColor Color () default Color.green;
 23 is 
24}

The default value annotation elements:

  Annotation elements must have a certain value, or default value specified in the definition of annotation, the annotation or specified when the value of non-essential elements annotation types can not be null. Thus, an empty string or 0 as the default value is a common practice. This constraint makes the processor difficult to demonstrate the presence or absence of a state element, because each statement annotation, all the elements are present, and have a corresponding value, in order to get around this constraint, we can define some special value, such as an empty string or negative, once represented an element does not exist, when you define for annotations, which has become an idiom.

Fruit vendor notes:

1 import java.lang.annotation.Documented;
 2 import java.lang.annotation.Retention;
 3 import java.lang.annotation.Target;
 4 import static java.lang.annotation.ElementType.FIELD;
 5 import static java.lang.annotation.RetentionPolicy.RUNTIME;
 6 
 7 
 8 /**
 9  * 水果供应者注解
10  */
11 @Target(FIELD)
12 @Retention(RUNTIME)
13 @Documented
14 public @interface FruitProvider {
15     / ** 
16 * Supplier number 
. 17       * / 
18 is      public  int ID () default -1 ;
 . 19      
20 is      / ** 
21 is supplier name * 
22 is       * / 
23 is      public String name () default "" ;
 24      
25      / ** 
26 is supplier address * 
27       * / 
28      public String address () default "" ;
 29}

Notes Processor: Get annotation information based on reflection

. 1 Import as java.lang.reflect.Field;
  2 
 . 3 / ** 
 . 4 * annotation processor 
 . 5   * / 
 . 6 public  class FruitInfoUtil {
  . 7      public  static  void getFruitInfo (<?> Class clazz) {
  . 8          
 . 9 strFruitName String = "fruit Name: " ;
 10 strFruitColor String =" fruit color: " ;
 . 11 strFruitProvicer String =" supplier information: " ;
 12 is          
13 is Field, [] = Fields clazz.getDeclaredFields ();
 14          
15          for (Field, Field: Fields) {
16             if(field.isAnnotationPresent(FruitName.class)){
17                 FruitName fruitName = (FruitName) field.getAnnotation(FruitName.class);
18                 strFruitName=strFruitName+fruitName.value();
19                 System.out.println(strFruitName);
20             }
21             else if(field.isAnnotationPresent(FruitColor.class)){
22                 FruitColor fruitColor= (FruitColor) field.getAnnotation(FruitColor.class);
23                 strFruitColor=strFruitColor+fruitColor.fruitColor().toString();
24                  System.out.println (strFruitColor);
 25              }
 26 is              the else  IF (field.isAnnotationPresent (FruitProvider. Class )) {
 27 FruitProvider fruitProvider = (FruitProvider) field.getAnnotation (FruitProvider. Class );
 28 strFruitProvicer = "Supplier Code: "+ fruitProvider.id () +" supplier name: "+ fruitProvider.name () +" supplier address: "+ fruitProvider.address ();
 29                  System.out.println (strFruitProvicer);
 30              }
 31 is          }
 32      }
 33}

Use notes:

. 1 Import test.FruitColor.Color;
  2 
 . 3 / ** 
 . 4 * Annotations use 
 . 5   * / 
 . 6 public  class the Apple {
  . 7      
 . 8 @FruitName ( "the Apple" )
  . 9      Private String appleName;
 10      
. 11 @FruitColor (fruitColor = Color.RED)
 12      Private String appleColor;
 13      
14 @FruitProvider (the above mentioned id = 1, name = "Shaanxi Fuji Group", address = "Xi'an, Shaanxi Province, Yan'an Road, Building 89 Fuji" )
 15      Private String appleProvider;
 16      
17      public  void setAppleColor(String appleColor) {
18         this.appleColor = appleColor;
19     }
20     public String getAppleColor() {
21         return appleColor;
22     }
23     
24     public void setAppleName(String appleName) {
25         this.appleName = appleName;
26     }
27     public String getAppleName() {
28         return appleName;
29     }
30     
31     public void setAppleProvider(String appleProvider) {
32         this.appleProvider = appleProvider;
33     }
34     public String getAppleProvider() {
35         return appleProvider;
36     }
37     
38     public void displayName(){
39         System.out.println("水果的名字是:苹果");
40     }
41 }
1 /**
2  * 输出结果
3  */
4 public class FruitRun {
5     public static void main(String[] args) {
6         FruitInfoUtil.getFruitInfo(Apple.class);
7     }
8 }

operation result:

Fruits Name: Apple 
fruit color: RED 
supplier number: 1 Supplier name: Shaanxi Fuji Group Supplier Address: Xi'an, Shaanxi Province, Yan'an Road, Building 89 Fuji

 

Guess you like

Origin www.cnblogs.com/jvStarBlog/p/12046305.html