1. 什么是注解
从字面上来看,注解就是注释、解释,实际上并不是这么简单的。他可以用于创建文档,跟踪代码中的依赖性,甚至执行基本编译时的检查。百度百科
2. 注解的作用是什么
2.1. 编写文档
通过代码里的表示的元数据生成文档【生成文本doc文档】,用法如下
/**
* @param a
* @param b
* @return
*/
public int add(int a, int b){
return 0;
}
对,没错,一般就是我们的doc注释,那么我们常见的注释有什么呢?
- @param 参数
- @author 作者
- @return 返回值
- @see 参考
- @since 一般指从那个版本开始
2.2. 代码分析
通过代码里的标示的元数据对代码进行分析,就像很多注解框架一样。
2.3. 编译检查
在编译时进行格式的检查,最常见的就是@Override,这里不在多说了。
3. 标准的Annotation
这里指的是java自带的几个Annotation,Override,Deprecated, SuppressWarnings。
4. 自定义Annotation
这里以运行时注解为例(ps:运行时注解的速度慢,应为在运行时用到反射的原因),关于编译时注解,前去看张鸿洋的博客。
先来看个简单的例子
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface Person {
String name() default "quanshijie";
int age() default 20;
boolean sex() default false;
}
- @Documented 是否将注解包含在JavaDoc中,
- @Retention 标示需要在什么级别保留该注释信息(生命周期)
- RetentionPolicy.SOURCE: 停留在java源文件
- RetentionPolicy.CLASS:停留在class文件中
- RetentionPolicy.RUNTIME:内存中的字节码,VM将在运行时也保留注解,因此可以通过反射机制读取注解的信息
- @Target 标示改注解可以用在什么地方
- @ElementType.CONSTRUCTOR 构造器声明
- @ElementType.FIELD 成员变量、对象、属性
- @ElementType.LOCAL_VARIABLE 局部变量声明
- @ElementType.METHOD 方法声明
- @ElementType.PACKAGE 包声明
- @ElementType.PARAMETER 参数声明
- @ElementType.TYPE 类、接口(包括注解类型)或enum声明
- @Inheried 允许子类集成父类中的注解
那么,我们现在来看看解析注释。代码如下:
@Person(name = "gl",age = 22,sex = true)
public class MyClass {
public static void main(String[] args){
if (MyClass.class.isAnnotationPresent(Person.class)){
Person person = MyClass.class.getAnnotation(Person.class);
System.out.println("name->"+person.name());
System.out.println("age->"+person.age());
System.out.println("sex->"+person.sex());
}
}
}
我们来看下解析中常用的几个方法。
method.getAnnotation(AnnotationName.class);
method.getAnnotations();
method.isAnnotationPresent(AnnotationName.class);
5. 我们常用的有那些
- ButterKnif
- retrofit
- ActiveAndroid
- 等等