`
linxizeng
  • 浏览: 102289 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Tiger学习 之 Annotate

阅读更多
主要有四种的标准的meta-annotation,都在java.lang.annotation的package中...

1.@Target指定那个程序单元可以有其所定义的annotation
(程序单元:class.interface,enum,field,method,parameter,constructor,variable package,annotation。参看ElementType类)

需要import(java.lang.annotation.ElementType;java.lang.annotation.Target;)两个类
引用

//只能用于TYPE和METHOD的程序单元
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface MyAnnotation {}
//只能用于自己
@Target({ElementType.ANNOTATION_TYPE})
public @interface MyAnnotation {}
//适用于所有,不要定义Targer
public @interface MyAnnotation {}


2.@Retention告诉Java编译器如何对待annotation,有三种情况(参见RetentionPolicy类)
需要import(java.lang.annotation.Retention;java.lang.annotation.RetentionPolicy;)两个类
SOURCE:Annotation会被编译器丢弃,如SuppressWarnings这个annotation
CLASS:保留在class的文件中,但会被VM忽略,默认的annotation
RUNTIME:保留在class的文件中且由VM读取
引用

@Retention(RetentionPolicy.CLASS)
public @interface MyAnnotation {}


3.@Documented定义annotation是否被视为注释在JavaDoc出现
需要import(java.lang.annotation.Documented)这个类

引用

@Documented
@Retention(RetentionPolicy.RUNTIME)
//使用@Documented就必须使用@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}


4.@Inherited,继承父类的annotation,仅仅用在subclass,且superclass的annotation全部继承下来。
需要import(java.lang.annotation.Inherited)这个类
引用

@Inherited
public @interface MyAnnotation {}

@MyAnnotation
public class Anno {
}
//SubAnno 会把Anno 的annotation继承下来
public class SubAnno extends Anno {
}

当然,如果子类的方法的覆盖父类带有annotation的方法是,改annotation是不会被继承的。
可以通过JavaDoc看效果...


关于Reflenting,annotation的自我减产工具,判断某个类具有什么也的annotation
如:判断时候是MyAnnotation类型的annotation)
引用

Class c = SubAnno.class;
System.out.println(c.isAnnotationPresent(MyAnnotation.class));

还要学习AnnotatedElement类...



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics