Asm 之 AnnotationVisitor 读取注解

Asm 中 AnnotationVisitor 用来处理注解。

测试代码:

1
2
3
4
5
6
7
package com.example.annotation;

public enum Color {
RED,
BLUE,
GREEN;
}

1
2
3
4
5
6
7
8
package com.example.annotation;

import java.io.Serializable;

@MyAnnotation(id = 1 , message="message" , names = {"A" , "B" ,"C"} , color = Color.BLUE)
public class MyClass implements @MyTypeAnnotation Serializable {

}
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.example.annotation;

import java.io.IOException;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;

public class AnnotationTest {

public static class MyClassVisitor extends ClassVisitor {
public MyClassVisitor() {
super(Opcodes.ASM5);
}

@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
return new MyAnnotationVisitor(super.visitAnnotation(desc, visible));
}



}

public static class MyAnnotationVisitor extends AnnotationVisitor {

public MyAnnotationVisitor( AnnotationVisitor av) {
super(Opcodes.ASM5,av);
}
/**
* 读取注解的值
*/
@Override
public void visit(String name, Object value) {
super.visit(name, value);
System.out.println(name + " = " + value );
}
/*
* 注解枚举的类型的值
*/
@Override
public void visitEnum(String name, String desc, String value) {
super.visitEnum(name, desc, value);
System.out.println("name ="+ name + ", desc="+desc +" , value=" + value);
}

@Override
public AnnotationVisitor visitAnnotation(String name, String desc) {
return super.visitAnnotation(name, desc);
}
/**
* 注解数组类型的值
*/
@Override
public AnnotationVisitor visitArray(String name) {
System.out.println("Array:" + name );
return new MyArrayAnnotationVisitor(super.visitArray(name));
}

}

public static class MyArrayAnnotationVisitor extends AnnotationVisitor{

public MyArrayAnnotationVisitor(AnnotationVisitor av) {
super(Opcodes.ASM5 , av);
}
/**
* 读取数组的内容
*/
@Override
public void visit(String name, Object value) {
super.visit(name, value);
System.out.println(name + " = " + value );
}


}

public static void main(String[] args) throws IOException {
ClassReader classReader = new ClassReader("com.example.annotation.MyClass");
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classReader.accept(new MyClassVisitor(),ClassReader.EXPAND_FRAMES);
}
}

测试结果:

1
2
3
4
5
6
7
id = 1
message = message
Array:names
null = A
null = B
null = C
name =color, desc=Lcom/example/annotation/Color; , value=BLUE

ASM 处理 数据的时候稍微有些繁琐,需要调用另一个 AnnotationVisitor, 调用其读取数据的方法读取内容。