
策略:
source /* Annotation信息仅存在于编译器处理期间,编译器处理完之后就没有该Annotation信息了 */
class /* 编译器将Annotation存储于类对应的.class文件中。默认行为 */
runtime /* 编译器将Annotation存储于class文件中,并且可由JVM读入 */
類型:
TYPE, /* 类、接口(包括注释类型)或枚举声明 */
FIELD, /* 字段声明(包括枚举常量) */
METHOD, /* 方法声明 */
PARAMETER, /* 参数声明 */
CONSTRUCTOR, /* 构造方法声明 */
LOCAL_VARIABLE, /* 局部变量声明 */
ANNOTATION_TYPE, /* 注释类型声明 */
PACKAGE /* 包声明 */
@Documented//可以出现在javadoc中
@Target(ElementType.TYPE)//修饰“类、接口(包括注释类型)或枚举声明”的注解
@Retention(RetentionPolicy.RUNTIME)//编译器会将该Annotation信息保留在.class文件中,并且能被虚拟机读取
public @interface MyAnnotation {
}
java 常用的Annotation:
@Deprecated -- @Deprecated 所标注内容,不再被建议使用。 @Override -- @Override 只能标注方法,表示该方法覆盖父类中的方法。 @Documented -- @Documented 所标注内容,可以出现在javadoc中。 @Inherited -- @Inherited只能被用来标注“Annotation类型”,它所标注的Annotation具有继承性。 @Retention -- @Retention只能被用来标注“Annotation类型”,而且它被用来指定Annotation的RetentionPolicy属性。 @Target -- @Target只能被用来标注“Annotation类型”,而且它被用来指定Annotation的ElementType属性。 @SuppressWarnings -- @SuppressWarnings 所标注内容产生的警告,编译器会对这些警告保持静默。
“@Deprecated和@Override”类似,“@Documented, @Inherited, @Retention, @Target”类似;
@Documented @Retention(RetentionPolicy.RUNTIME) public @interface Deprecated { }
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
String[] value();
}
例:@SuppressWarnings(value={"deprecation", "unchecked"})
deprecation -- 使用了不赞成使用的类或方法时的警告
unchecked -- 执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型。
fallthrough -- 当 Switch 程序块直接通往下一种情况而没有 Break 时的警告。
path -- 在类路径、源文件路径等中有不存在的路径时的警告。
serial -- 当在可序列化的类上缺少 serialVersionUID 定义时的警告。
finally -- 任何 finally 子句不能正常完成时的警告。
all -- 关于以上所有情况的警告。
a.class或method.isAnnotationPresent(b.class)//類a或方法是否包含類b(註解)
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class)//獲取方法的註解
Annotation[] annotations = method.getAnnotations()//獲取方法的所有註解
Annotation
原文:https://www.cnblogs.com/xblovexb/p/13364486.html