1、类型
(1)@SuppressWarnings
(2)@Deprecated
(3)@Override
(4)@Retention
指示注解类型的注解要保留多久,默认的为RetentionPolicy.CLASS。
RetentionPolicy:注解保留策略。
(4-1)SOURCE:编译器要丢弃的注解
(4-2)CLASS:编译器将注解记录在类文件中,但在运行时VM不需要保留注解
(4-3)RUNTIME:编译器将注解记录在类文件中,在运行时VM将保留注解,因此可以反射性的读取。
如上面@SuppressWarnings为SOURCE,@Deprecated的为RUNTIME,@Override为SOURCE
(5)@Target
指示注解类型所适用的程序元素的种类,如果注解类型声明中不存在Target元注解,则声明的类型可以用在任一程序元素上.如果存在这样的元注解,则编 译器强制实施指定的使用限制。
(5-1)@ElementType
ANNOTATION_TYPE:注解类型声明
CONSTRUCTOR:构造方法声明
FIELD:字段声明(包括枚举变量)
LOCAL_VARIABLE:局部变量声明
METHOD:方法声明
PACKAGE:包声明
PARAMETER:参数声明
TYPE:类,接口(包括注释类型)或枚举类型
如下例:定义一个Annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface DefineAnnotation {
}
package com.study.annotation;
@DefineAnnotation
public class TestAnnotation {
public static void main(String[] args) {
//判断该类是否使用了注解
boolean flag = TestAnnotation.class.isAnnotationPresent(DefineAnnotation.class);
if(flag){
DefineAnnotation annotation = TestAnnotation.class.getAnnotation(DefineAnnotation.class);
System.out.println(annotation);
}else{
System.out.println("The Class TestAnnotation cannot use DefineAnnotation!");
}
}
}
打印结果为:
@com.study.annotation.DefineAnnotation()
2、为注解添加属性
(1)为注解添加基本属性
//为注解DefineAnnotation添加基本属性
String name() default "yy";
使用注解
@DefineAnnotation(name="yuan")
System.out.println(annotation.name());
打印结果为:
yuan
因为采用了默认值,所以当使用DefineAnnotation注解时,可以不指定name属性,此时打印的结果为默认值yy。
当注解只有一个属性value时,在使用注解时,可以直接赋值,即@DefineAnnotation(value值).
(2)添加高级属性
//为注解DefineAnnotation添加高级属性
int[] arrAtt();
使用:
@DefineAnnotation(name="yuan",arrAtt={1,2,3,4})
System.out.println(annotation.arrAtt().length);
结果为:
4
(3)添加枚举
首先添加一个枚举类:
package com.study.annotation;
public enum CarEnum {
AUDI{
public String getName(){
return "audi";
}
},
BMW{
public String getName(){
return "bmw";
}
};
public abstract String getName();
}
使用:
@DefineAnnotation(name="yuan",arrAtt={1,2,3,4},car=CarEnum.AUDI)
System.out.println(annotation.car().getName());
结果为:
audi
(4)添加注解属性
首先定义另外一个注解:
public @interface OtherAnnotation {
String value();
}
然后在注解DefineAnnotation中添加此注解
OtherAnnotation annotationAttr() default @OtherAnnotation("yyyy");
使用:
@DefineAnnotation(name="yuan",arrAtt={1,2,3,4},car=CarEnum.AUDI,annotationAttr=@OtherAnnotation("yuany"))
System.out.println(annotation.annotationAttr().value());
结果:
yuany