What is an annotation?
Annotations, as the name implies, annotations,is to add a note to a thing, which will hold some information that might be useful for a later time period.Java Annotations are also called Java Annotations, andJava provides a set of mechanisms that allow us to add standards ( that is, some information )to methods, classes, parameters, packages, fields, and variables. And, at a later time, the annotated information is extracted for use by reflection.
By using annotation, a program developer can embed some supplemental information in the source file without changing the original logic.
Annotation can be used to decorate classes, properties, methods, and annotation does not affect the execution of programs, whether or not annotation code is used.
Annotation is divided into three kinds: annotation, meta-annotations and custom annotation in the system
The annotation in the system are divided into:
@Override: Can only be used on a method, indicating that the current method definition overrides a method in the superclass.
@Deprecated: You can set all the elements in the program.
@SuppressWarnings: Temporarily turn off some warning message messages.
Meta-Annotations:
Meta-annotations are annotations that define annotations, meaning that these meta-annotations are used specifically to constrain other annotations.
There are four main elements of meta-annotations:
@Target, @Retention, @Documented, @Inherited
@Target
@Target:表示该注解用于什么地方 @Target(ElementType.TYPE) //接口、类、枚举、注解 @Target(ElementType.FIELD) //字段、枚举的常量 @Target(ElementType.METHOD) //方法 @Target(ElementType.PARAMETER) //方法参数 @Target(ElementType.CONSTRUCTOR) //构造函数 @Target(ElementType.LOCAL_VARIABLE)//局部变量 @Target(ElementType.ANNOTATION_TYPE)//注解 @Target(ElementType.PACKAGE) ///包 由以上的源码可以知道,他的elementType 可以有多个,一个注解可以为类的,方法的,字段的等等
@Retention (valid time for annotations)
@Retention: 定义注解的保留策略 @Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含 @Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得, @Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
@Documented
@Document:说明该注解将被包含在javadoc中
@Inherited
@Inherited:说明子类可以继承父类中的该注解
Custom annotation:
Why custom annotation? because the only three annotations within the system do not meet the needs of our actual use.
The custom step is broadly divided into two steps:1The annotation name is declared by @interface keyword ( note, not interface, @interace) , as well as the member properties of the annotations or parameters called annotations. 2use the four meta-annotations built into Java to limit the functionality and scope of this custom callout. A simple example: Customizing a class-level callout Description
Packagelighter.javaeye.com; Importjava.lang.annotation.Documented; ImportJava.lang.annotation.ElementType; Importjava.lang.annotation.Retention; ImportJava.lang.annotation.RetentionPolicy; ImportJava.lang.annotation.Target; @Target (Elementtype.type)//This annotation is applied to the class@Retention (Retentionpolicy.runtime)//labels are persisted to the runtime@Documented//include this note in the Javadoc Public@InterfaceDescription {String value (); }
Define a method-level annotation Name again
Packagelighter.javaeye.com; Importjava.lang.annotation.Documented; ImportJava.lang.annotation.ElementType; Importjava.lang.annotation.Retention; ImportJava.lang.annotation.RetentionPolicy; ImportJava.lang.annotation.Target; //Note that the @target here are different from the @description, and the parameter members are different .@Target (Elementtype.method) @Retention (retentionpolicy.runtime) @Documented Public@InterfaceName {String originate (); String community (); }
then use the above two annotations
Packagelighter.javaeye.com; @Description (Value= "Javaeye, make the best software development Exchange Community") Public classJavaeyer {@Name (originate= "Founder: Robbin", community= "Javaeye") PublicString GetName () {return NULL; } @Name (Originate= "Founder: Jiangnan White", community= "Springside") PublicString getName2 () {return"Borrow two-bit ID one, write this example, please forgive me!"; }}
Description: It labeled "@Description (value=" Javaeye, do the best software development Exchange Community "), can be written as"@Description ("Javaeye, The best software Development Exchange Community ") , the result is the same. Because the parameter ( or attribute ) is valuewhen the Description dimension is defined. While value is special, it can be written without display when the parameter is specified. Of course, if the parameter name is not value but other such as des, when you define it, you must display the name of the parameter when using the annotation, and then assign the value:@Description (des= "xxx")
Extracting the information from the annotations
Packagelighter.javaeye.com; ImportJava.lang.reflect.Method;ImportJava.util.HashSet;ImportJava.util.Set; Public classtestannotation {/*** Author Lighter * Description: For specific're wrong about annotation API usage See Javadoc documentation*/ Public Static voidMain (string[] args)throwsException {String class_name= "Lighter.javaeye.com.JavaEyer"; Class Test=Class.forName (class_name); Method[] Method=Test.getmethods (); BooleanFlag = Test.isannotationpresent (Description.class); if(flag) {Description des= (Description) test.getannotation (Description.class); System.out.println ("Description:" +Des.value ()); System.out.println ("-----------------"); } //Save all the methods of javaeyer that have been used to @name to set .Set<method> set =NewHashset<method>(); for(inti=0;i<method.length;i++) { BooleanOtherflag = Method[i].isannotationpresent (Name.class); if(Otherflag) Set.add (Method[i]); } for(Method m:set) {name Name= M.getannotation (Name.class); System.out.println (Name.originate ()); System.out.println ("Community created:" +name.community ()); } }}Precautions :all Annotation will automatically inherit the java.lang.annotation interface , so it is no longer possible to inherit another class or interface . The most important point is how to set the parameters of the Annotation type : First, it can only be decorated with public or default access rights. For example , String value (); This sets the method to the defaul default type . Second, parameter members can only use basic types Byte,short,char,int,long,float,double,boolean Eight basic data types and String, data types such as Enum,class,annotations , and arrays of these types . For example , String value (); The parameter member here is String. Annotations are often used in conjunction with reflection, enumeration, and the following are some enumerations and customizations that set the default worth of code:
Public enum name { XML, zml, CML; } public @Interface mytest { publicdefault name.zml; } = name.cml) class demo{ }
This article extensively references the article: http://wanqiufeng.blog.51cto.com/409430/458883