The principle of Annotation Annotation custom annotation examples
What is a comment?
For many developers the initial contact, we should have this question? 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.
Common standards Annotation:
1.) Override
java.lang.Override type of annotation is a marker, which is used as a labeling method. It illustrates a method is marked overloading of a parent class, the assertion played a role. If we use this annotation in a method of the parent class method does not cover, java compiler warning will be a compilation error.
2.) of Deprecated in
of Deprecated in is a type of marker annotations. When using a type or type member @Deprecated modified, then the compiler will not encourage the use of this program element is marked. Therefore, the use of this modification has a certain "continuity": If we covered through inheritance or in code mode using this obsolete type or member, or members, although the type of inheritance or is not covered after being declared as @Deprecated, but the compiler still reported to the police.
3.) SuppressWarnings
SuppressWarning not a mark type annotations. It has a type of String [] members, is a member of the banned warning name. For javac compiler is concerned, the option is -Xlint effective warning to @SuppressWarings name is also effective, but the compiler does not recognize ignored warnings name.
@SuppressWarnings ( "unchecked")
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 example:
FruitName.java
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 * Fruit comment Name 9 */ 10 @Target(FIELD) 11 @Retention(RUNTIME) 12 @Documented 13 public @interface FruitName { 14 String value() default ""; 15 }
FruitColor.java
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 * Fruit color comment 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 19 /** * 20 color attributes 21 */ 22 Color fruitColor() default Color.GREEN; 23 24 }
FruitProvider.java
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 * Fruit supplier notes 10 */ 11 @Target(FIELD) 12 @Retention(RUNTIME) 13 @Documented 14 public @interface FruitProvider { 15 /** 16 * Supplier number 17 */ 18 public int id() default -1; 19 20 /** 21 * Vendor Name 22 */ 23 public String name() default ""; 24 25 /** 26 * Supplier Address 27 */ 28 public String address() default ""; 29 }
FruitInfoUtil.java
1 import java.lang.reflect.Field; 2 3 /** 4 * Annotation Processor 5 */ 6 public class FruitInfoUtil { 7 public static void getFruitInfo(Class<?> clazz){ 8 9 String strFruitName = "fruit name:"; 10 String strFruitColor = "Fruit Color:"; 11 String strFruitProvicer = "Supplier Information:"; 12 13 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 else if(field.isAnnotationPresent(FruitProvider.class)){ 27 FruitProvider fruitProvider= (FruitProvider) field.getAnnotation(FruitProvider.class); 28 strFruitProvicer = "supplier number:" + fruitProvider.id () + "Supplier name:" + fruitProvider.name () + "Supplier Address:" + fruitProvider.address (); 29 System.out.println(strFruitProvicer); 30 } 31 } 32 } 33 }
Apple.java
1 import test.FruitColor.Color; 2 3 /** * Use 4 Notes 5 */ 6 public class Apple { 7 8 @FruitName("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, Fuji Building 89") 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 = apple name; 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 ( "is the name of the fruit: apple"); 40 } 41 }
FruitRun.java
1 /** Output 2 * 3 */ 4 public class FruitRun { 5 public static void main(String[] args) { 6 FruitInfoUtil.getFruitInfo(Apple.class); 7 } 8 }
Operating results are:
Fruits Name: Apple
fruit color: RED
Supplier Code: Supplier Name 1: Shaanxi Fuji Group Supplier Address: Xi'an, Shaanxi Province, Yan'an Road, Building 89 Fuji
参考链接:
[1]http://www.cnblogs.com/peida/archive/2013/04/26/3038503.html
[2]http://www.cnblogs.com/whoislcj/p/5671622.html
[3]http://blog.csdn.net/lylwo317/article/details/52163304
What is a comment?
For many developers the initial contact, we should have this question? 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.
Common standards Annotation:
1.) Override
java.lang.Override type of annotation is a marker, which is used as a labeling method. It illustrates a method is marked overloading of a parent class, the assertion played a role. If we use this annotation in a method of the parent class method does not cover, java compiler warning will be a compilation error.
2.) of Deprecated in
of Deprecated in is a type of marker annotations. When using a type or type member @Deprecated modified, then the compiler will not encourage the use of this program element is marked. Therefore, the use of this modification has a certain "continuity": If we covered through inheritance or in code mode using this obsolete type or member, or members, although the type of inheritance or is not covered after being declared as @Deprecated, but the compiler still reported to the police.
3.) SuppressWarnings
SuppressWarning not a mark type annotations. It has a type of String [] members, is a member of the banned warning name. For javac compiler is concerned, the option is -Xlint effective warning to @SuppressWarings name is also effective, but the compiler does not recognize ignored warnings name.
@SuppressWarnings ( "unchecked")
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 example:
FruitName.java
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 * Fruit comment Name 9 */ 10 @Target(FIELD) 11 @Retention(RUNTIME) 12 @Documented 13 public @interface FruitName { 14 String value() default ""; 15 }
FruitColor.java
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 * Fruit color comment 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 19 /** * 20 color attributes 21 */ 22 Color fruitColor() default Color.GREEN; 23 24 }
FruitProvider.java
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 * Fruit supplier notes 10 */ 11 @Target(FIELD) 12 @Retention(RUNTIME) 13 @Documented 14 public @interface FruitProvider { 15 /** 16 * Supplier number 17 */ 18 public int id() default -1; 19 20 /** 21 * Vendor Name 22 */ 23 public String name() default ""; 24 25 /** 26 * Supplier Address 27 */ 28 public String address() default ""; 29 }
FruitInfoUtil.java
1 import java.lang.reflect.Field; 2 3 /** 4 * Annotation Processor 5 */ 6 public class FruitInfoUtil { 7 public static void getFruitInfo(Class<?> clazz){ 8 9 String strFruitName = "fruit name:"; 10 String strFruitColor = "Fruit Color:"; 11 String strFruitProvicer = "Supplier Information:"; 12 13 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 else if(field.isAnnotationPresent(FruitProvider.class)){ 27 FruitProvider fruitProvider= (FruitProvider) field.getAnnotation(FruitProvider.class); 28 strFruitProvicer = "supplier number:" + fruitProvider.id () + "Supplier name:" + fruitProvider.name () + "Supplier Address:" + fruitProvider.address (); 29 System.out.println(strFruitProvicer); 30 } 31 } 32 } 33 }
Apple.java
1 import test.FruitColor.Color; 2 3 /** * Use 4 Notes 5 */ 6 public class Apple { 7 8 @FruitName("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, Fuji Building 89") 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 = apple name; 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 ( "is the name of the fruit: apple"); 40 } 41 }
FruitRun.java
1 /** Output 2 * 3 */ 4 public class FruitRun { 5 public static void main(String[] args) { 6 FruitInfoUtil.getFruitInfo(Apple.class); 7 } 8 }
Operating results are:
Fruits Name: Apple
fruit color: RED
Supplier Code: Supplier Name 1: Shaanxi Fuji Group Supplier Address: Xi'an, Shaanxi Province, Yan'an Road, Building 89 Fuji
参考链接:
[1]http://www.cnblogs.com/peida/archive/2013/04/26/3038503.html
[2]http://www.cnblogs.com/whoislcj/p/5671622.html
[3]http://blog.csdn.net/lylwo317/article/details/52163304