一、JDK内置注解
@Override,只能用于子类方法,表示重写父类方法
@Deprecad,表示过期
@SuppressWarning,抑制编译器警告,不会编译到.class文件中
二、自定义注解
简单版,无成员,仅作为标识:
// 定义注解
public @interface MyAnnotation {
}
// 使用注解
@MyAnnotation
class AnnotationTest {
}
有成员的注解:
// 定义注解
public @interface MyAnnotation {
String value() default "defaultValue";
}
//使用默认值
@MyAnnotation
class AnnotationTest {
String value;
}
//使用非默认值,定义时无default必须制定值
@MyAnnotation("myValue")
class AnnotationTest {
String value;
}
三、使用元注解
1)@Retention(RetentionPolicy.*):指定此注解的生命周期
- RetentionPolicy.SOURCE,不编译到.class文件
- RetentionPolicy.CLASS(默认),编译到.class文件,但执行时不会加载到内存
- RetentionPolicy.RUNTIME,编译到.class文件,执行时会加载到内存,只有RUNTIME的注解才可通过反射获取
2)@Target(*):指定此注解可修饰的元素
- TYPE:接口、类、枚举、注解
- FIELD:字段、枚举的常量
- METHOD:方法
- PARAMETER:方法参数
- CONSTRUCTOR:构造函数
- LOCAL_VARIABLE:局部变量
- ANNOTATION_TYPE:注解
- PACKAGE:包
- TYPE_PARAMETER:泛型参数
- TYPE_USE:
- MODULE:
3)Documented:此注解被javadoc解析时保留,默认不保留
4)Inherited:此注解修饰的类会自动被子类继承
// 定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 生命周期为CLASS,只可修饰类,注解
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE,ElementType.ANNOTATION_TYPE})
public @interface MyAnnotation {
String value() default "defaultValue";
}
// 使用注解
@MyAnnotation("myValue")
class AnnotationTest {
String value;
//提示'@MyAnnotation' not applicable to method,不可修饰方法,因为@Target中未设置METHOD
//@MyAnnotation
void test(){
};
}
四、反射获取注解信息
// 定义注解,声明周期必须为RetentionPolicy.RUNTIME
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.ANNOTATION_TYPE,ElementType.METHOD})
public @interface MyAnnotation {
String value() default "defaultValue";
}
// 定义类,注解修饰
@MyAnnotation("myValue")
class AnnotationTest {
}
// 反射获取注解
import java.lang.annotation.Annotation;
class JavaStudy {
public static void main(String[] args) {
// 获取注解的元注解
Class clazz = MyAnnotation.class;
Annotation[] annotations = clazz.getAnnotations();
for (int i = 0; i < annotations.length ; i++) {
System.out.println(annotations[i]);
}
// 获取类的注解,Retention必须为RUNTIME才可被获取
Class clazz1 = AnnotationTest.class;
Annotation[] annotations1 = clazz1.getAnnotations();
for (int i = 0; i < annotations1.length ; i++) {
System.out.println(annotations1[i]);
}
}
}