————————————————
原文链接:https://blog.csdn.net/qq_35972907/article/details/97753257
————————————————
@interface 不是interface,是注解类 定义注解
是jdk1.5之后加入的,java没有给它新的关键字,所以就用@interface 这么个东西表示了
这个注解类,就是定义一个可用的注解,包括这个注解用于什么地方,是类,还是方法,还是property,还是方法入参等等
@Inherited //这个Annotation 可以被继承
@Documented //这个Annotation可以被写入javadoc
@Retention(RetentionPolicy.RUNTIME)
注解@Retention可以用来修饰注解,是注解的注解,称为元注解。
public enum RetentionPolicy {
SOURCE, // 编译器处理完Annotation后不存储在class中
CLASS, // 编译器把Annotation存储在class中,这是默认值
RUNTIME // 编译器把Annotation存储在class中,可以由虚拟机读取,反射需要
}
@Target:注解的作用目标
@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) ///包
Annotation的一般形式是 :
public @interface MyAnnotation {
String value() default "hahaha";
}
public class MyAnnotation extends java.lang.annotation.Annotation{
private String value = "hahaha";
public void setValue(String value){
this.value = value;
}
public String getValue(){
return value;
}
}
@MyAnnotation(value="hello") //对应Bean的set方法
Method method = AnnotationTest.class.getMethod("doSomthing", null); //取得被注释的方法,AnnotationTest.class为该方法所在的类
MyRetention mr = method.getAnnotation(MyRetention.class); //取得注释对象
String value = mr.value(); //取得value的值,对应Bean的get方法.