定义Annotation的语法:
Public @interface Annotation的名称{}
如:public @interface Override
public @interface MyAnnotation {
}
任何一个自定的Anntation都是继承了java.lang.annotation.Annotation接口
一个Annotation如果要想起作用,则肯定要依靠反射机制,通过反射可以取得在一个方法上声明的Annotation的全部内容。
具体实例
自定义Annotation:MyAnnotation
- 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;
- @Target(ElementType.CONSTRUCTOR)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface MyAnnotation {
- public String name() default "singsong";
- }
1. @Target(ElementType.CONSTRUCTOR)
@Target指示注释类型所适用的程序元素的种类。如果注释类型声明中不存在 Target 元注释,则声明的类型可以用在任一程序元素上。如果存在这样的元注释,则编译器强制实施指定的使用限制。参数是ElementType: java.lang.annotation.ElementType
定义:public enum ElementTypeextends Enum<ElementType>是枚举类型
ElementType.CONSTRUCTOR代表此Annotation必须声明在构造方法声明的上面,而不能写在任何的method{}(方法)或者是field(属性)的上方。
@Target: 表示该注解可以用于什么地方。可用ElementType枚举类型主要有:
TYPE : 类、接口或enum声明
FIELD: 域(属性)声明
METHOD: 方法声明
PARAMETER: 参数声明
CONSTRUCTOR: 构造方法声明
LOCAL_VARIABLE:局部变量声明
ANNOTATION_TYPE:注释类型声明
PACKAGE: 包声明
2.@Retention(RetentionPolicy.RUNTIME)
@Retention指示注释类型的注释要保留多久。如果注释类型声明中不存在 Retention 注释,则保留策略默认为 RetentionPolicy.CLASS。 只有元注释类型直接用于注释时,Target 元注释才有效。如果元注释类型用作另一种注释类型的成员,则无效。
Retention设为了RUNTIME,代表此annotation的具体实现可以在运行时用类反射来实现
RetentionPolicy定义:public enum RetentionPolicyextends Enum<RetentionPolicy>属于枚举类型
可用RetentionPolicy枚举类型主要有:
SOURCE: 注解将被编译器丢弃。
CLASS : 注解在class文件中可能。但会被VM丢弃。
RUNTIME: VM将在运行时也保存注解(如果需要通过反射读取注解,则
使用该值)。
3. @Documented
@Documented: 将此注解包含在Javadoc中。
4. Annotation需要声明:public @interface MyAnnotation{***}
使用自定义的MyAnnotation
- public class Person {
- @MyAnnotation(name = "The person's name is singsong")
- Person() {
- }
- public String name;
- }
使用java反射机制来实现MyAnnotation
- import java.lang.reflect.Method;
- public class TestMyAnnotation {
- public static void main(String[] args) throws Exception {
- Class<Person> c = Person.class;
- Method method = c.getMethod("getName");
- MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
- System.out.println(myAnnotation.name());
- }
- }
运行结果:
The person's name is singsong