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;)两个类
[quote]
//只能用于TYPE和METHOD的程序单元
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface MyAnnotation {}
//只能用于自己
@Target({ElementType.ANNOTATION_TYPE})
public @interface MyAnnotation {}
//适用于所有,不要定义Targer
public @interface MyAnnotation {}
[/quote]

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读取
[quote]
@Retention(RetentionPolicy.CLASS)
public @interface MyAnnotation {}
[/quote]

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

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

4.@Inherited,继承父类的annotation,仅仅用在subclass,且superclass的annotation全部继承下来。
需要import(java.lang.annotation.Inherited)这个类
[quote]
@Inherited
public @interface MyAnnotation {}

@MyAnnotation
public class Anno {
}
//SubAnno 会把Anno 的annotation继承下来
public class SubAnno extends Anno {
}
[/quote]
当然,如果子类的方法的覆盖父类带有annotation的方法是,改annotation是不会被继承的。
可以通过JavaDoc看效果...


关于Reflenting,annotation的自我减产工具,判断某个类具有什么也的annotation
如:判断时候是MyAnnotation类型的annotation)
[quote]
Class c = SubAnno.class;
System.out.println(c.isAnnotationPresent(MyAnnotation.class));
[/quote]
还要学习AnnotatedElement类...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值