Java 注解

注解

what:用于描述数据,并且可以被编译期以及jvm捕获的信息

  • 注解基本使用
  • 运行时处理注解
  • 编译处理注解
  • 其它用处

注解基本使用

how:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//定义
@interface One{
//类似方法声明的方式来声明属性
String name();
}
//使用
class A {
@One(name = "fdaf")
private int test() {

}
}
//基本注解
@Overrider 描述限定重现父类方法
@Deprecated 描述某个类或方法过时
@SupressWarnings 抑制编译期警告

元注解:描述注解的注解,用于限定注解的行为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Target 描述注解将注解的位置。
public enum ElementType {
TYPE, //类,接口,注解,枚举
FIELD,//属性
METHOD,//方法
PARAMETER,//参数
CONSTRUCTOR,//构造方法
LOCAL_VARIABLE,//局部变量
ANNOTATION_TYPE,//注解
PACKAGE,//包
TYPE_PARAMETER,//Type parameter declaration
TYPE_USE//Use of a type
}
@Retention
以下三种
public enum RetentionPolicy {
SOURCE,
CLASS,
RUNTIME
}

@Documented 表示可以被javadoc工具提取成文档
@Inherited 表示继承性,如果某个使用了该注解修饰的注解,那么其子类会自动具有该注解

通过注解在相应的位置,我们可以在下面的注解处理器,或者反射处理,获得到我们想要的得到的数据。这就是注解的任务啦。

运行处理注解

通过反射获得Class对象,Method等等,从而通过getAnnotation继而获得值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package learn2;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

public class AnnotationTest {
public static void main(String[] args) {
AnnotationTest test = new AnnotationTest();
test.test();
}

@TestAnnotation(msg = "test")
public int someOne;

private void test() {
Class clazz = getClass();
try {
Field field = clazz.getField("someOne");
String msg = field.getAnnotation(TestAnnotation.class).msg();
System.out.println(field.getAnnotation(TestAnnotation.class));
System.out.println(msg);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}

}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface TestAnnotation{
String msg();
}
}

编译处理注解

编译时处理注解,生成java文件

处理注解时的相关类和API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//接口
AnnotatedElement // 被注解的元素,这个接口声明的方法包含了一些获得注解注解对象的方法
AnnotatedType //被注解的类型,有一个getType的方法//这些接口都从1.8开始的,感觉和泛型相关
AnnotatedArrayType //被注解的数组类型
AnnotatedParameterizedType//被注解的参数化类型
AnnotatedTypeVariable//被注解的类型变量
AnnotatedWildcardType//被注解的统配符类型 获取上界和下界的AnnotatedType
//类
Filed
Class
Method
Package
Construcotr
Paramter
Executable
AccessibleObject

注解一个普通的int产生的AnnotatedType对象是sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl@1d44bcfa
而注解List<String> list类型产生的的AnnotatedType对象是sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedParameterizedTypeImpl@1d44bcfa
而对int[] list 产生的是
sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedArrayTypeImpl@1d44bcfa
与之对应的是那几个接口的实现类,虽然我没搞懂有啥用。。

其它用处

用于设定常量