介绍
1、注解的保留策略:
@Retention(RetentionPolicy.SOURCE) // 注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
2、注解的作用目标:
@Target(ElementType.TYPE) // 接口、类、枚举、注解
@Target(ElementType.FIELD) // 字段、枚举的常量
@Target(ElementType.METHOD) // 方法
@Target(ElementType.PARAMETER) // 方法参数
@Target(ElementType.CONSTRUCTOR) // 构造函数
@Target(ElementType.LOCAL_VARIABLE) // 局部变量
@Target(ElementType.ANNOTATION_TYPE) // 注解
@Target(ElementType.PACKAGE) // 包
3.注解包含在javadoc中:
@Documented
4.注解可以被继承:
@Inherited
##自定义注解
public class testAnnotation {
public static void main(String[] args) throws NoSuchMethodException {
Method test01 = (Method) testAnnotation.class.getMethod("test01");
annotationTest annotation = (annotationTest) test01.getAnnotation(annotationTest.class);
// 没有定义在类上面的注解,所以取出为null
// annotationTest annotation = (annotationTest) testAnnotation.class.getAnnotation(annotationTest.class);
annotation.value();
System.out.println(annotation.value());
}
@annotationTest("hahah")
public static void test01(){
}
}
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface annotationTest{
String value();
}