什么是注解?
java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。包含在 java.lang.annotation 包中。
有哪些注解
java中元注解有四个: @Retention @Target @Document @Inherited;
@Retention:注解的保留位置
- @Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含
- @Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
- @Retention(RetentionPolicy.RUNTIME) // 注解会在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) ///包
@Document:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解
例子: 定义一个注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Document
public @interface AnnatDemo{
public int value();
}
使用注解作用于以下方法:
public class Demo {
@AnnatDemo(1)
public String hello(...);
}
进行反射获取: (可写在切面中,进行一些权限等操作)
//反射得到类,省略
Method[] methods=class.getDeclaredMethods();
for(Method method : methods){
AnnatDemo annat = method.getAnnotation(AnnatDemo.class);
if(annat != null){
int value = annat.value();
System.out.println("value:"+value);
}
}