DLancerC

Java Annotation

Java Annotation是JDK5.0引入的一种注释机制。随着 Spring 引入了大量的注释类,相比 XML 配置,注释配置更受欢迎,有进一步流行的趋势。可以通过 自定义一些注释来很大程度上减少代码。深入学习注解,就必须能定义自己的注解,并使用注解,在定义自己的注解之前,就必须要了解Java提供的元注解和相关定义注解的语法。

定义

  1. Annotaiion需要声明为@interface

  2. @Target规定注释一定要写在什么语句上面
    @Target(ElementType.对应类型)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    TYPE: 类,接口或者Enum声明
    FIELD: 域(属性)声明
    METHOD: 方法声明
    PARAMETER: 参数申明
    CONSTRUCTOR: 构造方法声明
    LOCAL_VARIABLE: 局部变量声明
    ANNOTATION_TYPE: 注释类声明
    PACKAGE: 包声明
    Java 8 之前的版本中,只能允许在声明式前使用 Annotation
    (Annotaion可以在任何使用Type的地方)
    TYPE_PARAMETER: Type 的声明式前
    TYPE_USE: 所有使用 Type 的地方(如:泛型,类型转换等)
  3. @Retention 需要在什么级别保存该注释信息
    @Retention(RetentionPolicy.对应类型)

    SOURCE: 注释将被编译器丢弃,例如@Override,这种只起到标示的注释
    CLASS: 注释在class中,但是会被VM丢弃
    RUNTIME: 注释在class中,VM中也会存在
    
  4. @Documented 将此注解包含在Javadoc中

使用

注释

1
2
3
4
5
6
7
8
9
10
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValueBind {
enum fieldType{
STRING,INT
}
fieldType type();
String value();
}

使用的Bean对象

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
public class Student implements Serializable {
private String studentId;
private int age;
private String name;
public String getStudentId() {
return studentId;
}
@ValueBind(type = ValueBind.fieldType.STRING,value = "7777")
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public int getAge() {
return age;
}
@ValueBind(type = ValueBind.fieldType.INT,value = "21")
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
@ValueBind(type = ValueBind.fieldType.STRING,value = "wuyu")
public void setName(String name) {
this.name = name;
}
}

测试

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 static void main(String[] args) throws Exception {
Object c = Class.forName("Student").newInstance();
/**
* getMethod*() 获取的是类的public method
* including those declared by the class(自己) or interface(接口) and those inherited from superclasses and superinterfaces(父类,父接口)
* getDeclaredMethod*() 只得到自身申明的所有方法,
* 包括public, protected, default (package) access, and private methods, but excluding inherited methods
*
* 对应没有method返回一个length=0 Array
*/
Method[] methodArray = c.getClass().getDeclaredMethods();
for (Method method: methodArray) {
if(method.isAnnotationPresent(ValueBind.class)){
ValueBind annotation = method.getAnnotation(ValueBind.class);
String type = String.valueOf(annotation.type());
String value = annotation.value();
if("INT".equals(type)){
method.invoke(c,new Integer(value));
}else{
method.invoke(c,value);
}
}
}
AnnotationDemo1 annotationStudent = (AnnotationDemo1) c;
System.out.println("StudentId===="+annotationStudent.getStudentId());
System.out.println("StudentName===="+annotationStudent.getName());
System.out.println("StudentAge===="+annotationStudent.getAge());
}