Java 注解

Annotation的作用:
1.不是程序本身,可以对程序作出解释。(这一点,跟注释没什么区别)
2.可以被其他程序(比如:编译器,其他类(通过反射))读取。(注解信息处理流程,是注解和注释的重大区别如果没有注解信息处理流程,则注解毫无意义)
Annotation的格式:
注解是以“@注释名”在代码中存在的,还可以添加一些参数值,例如:
@SuppressWarnings(value=”unchecked”)。(抑制警告)
Annotation在哪里使用:
可以附加在package, class, method, field等上面,相当于给它们添加了额外的辅助信息,我们可以通过反射机制编程实现对这些元数据的访问。
自定义注解:
格式:public @interface 注解名 {定义体}
1.方法的名称就是参数的名称;
2.返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum);
3.可以通过default来声明参数的默认值1;
4.如果只有一个参数成员,一般参数名为value;
元注解:
元注解的作用就是负责注解其他注解。 Java定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。
1.@Target:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
ElementType.TYPE;ElementType.FIELD…
2.@Retention:表示需要在什么级别保存该注释信息,用于描述注解的生命周期
SOURCE;CLASS;RUNTIME(可被反射机制读取)
3.@Documented
4.@Inherited
通过反射读取注解的流程:

  • 自定义类注解:
1
2
3
4
5
@Target(value = {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface test01Table {
String value();
}
  • 自定义属性注解:
1
2
3
4
5
6
7
@Target(value = {ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface test01Field {
String columnName();
String type();
int length();
}
  • 在test01中加入注解:
1
2
3
4
5
6
7
8
9
@test01Table("tb_member")
public class test01 {
@test01Field(columnName = "id", type = "int", length = 10)
private int id;
@test01Field(columnName = "sname", type = "varchar", length = 10)
private String name;
@test01Field(columnName = "age", type = "int", length = 3)
private int age;
}
  • 读取test01中的注解:
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
/**
* 通过反射读取自定义注解
*/
public class ReadAnnotation {
public static void main(String[] args) {
try {
Class clazz = Class.forName("com.sgg.annotation.test01");
//获得类的有效注解
Annotation[] annotations = clazz.getAnnotations();
for(Annotation a : annotations){
System.out.println(a);
}

//获得类的制定注解
test01Table tt = (test01Table)clazz.getAnnotation(test01Table.class);
System.out.println(tt.value());

//获得类的属性的对应注解
Field f = clazz.getDeclaredField("id");
test01Field tf = (test01Field)f.getAnnotation(test01Field.class);
System.out.println(tf.columnName() +"--"+ tf.type() +"--"+ tf.length());

//接下来可以利用注解信息写出DDL语句,完成相应的数据库操作
} catch (Exception e) {
e.printStackTrace();
}
}
}

  1. 1.注解元素必须要有值。我们定义注解元素时,经常使用空字符串、0作为默认值。也经常使用负数(比如:-1)表示不存在的含义