Preface
At present, more and more architectural designs are using annotations, such as spring3.0, struts2 and other frameworks. Let's first look at the definition of the annotation. The following is a code that uses JDK 5 Annotation @Target:
@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface AsynLog { }1. Usage of @Target
java.lang.annotation.Target
Used to set the scope of annotation usage
java.lang.annotation.ElementType
Target specifies annotation scopes to use enumeration collections
2. Usage of ElementType
| Get the value | Annotation scope |
| METHOD | Can be used in methods |
| TYPE | Can be used on classes or interfaces |
| ANNOTATION_TYPE | Can be used on annotation types (types modified by @interface) |
| CONSTRUCTOR | Can be used in construction methods |
| FIELD | Can be used on the domain |
| LOCAL_VARIABLE | Can be used on local variables |
| PACKAGE | Used to record package information of java files |
| PARAMETER | Can be used on parameters |
Here is a highlight: ElementType. PACKAGE. It is not used in general classes, but in the fixed file package-info.java. It should be emphasized here that the naming must be "package-info". Since package-info.java is not a legal class, using eclipse to create a class will prompt that it is illegal, so you need to create package-info.java in the way of creating a file.
For example, a range PACKAGE can be used to define:
@Target({ElementType.PACKAGE,ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface AsynLog { }Then, create the file: package-info.java, with the content as follows:
The code copy is as follows:
@AsynLog
package org.my.commons.logs.annotation;
Keynote: Annotations can only be used within the range set by ElementType, otherwise an error will be compiled. For example: the scope only contains ElementType.METHOD, which means that the annotation can only be used on the class method, and the exception will be compiled outside the scope of use.