Asm 之 visitTypeAnnotation

Asm 中 visitAnnotation 方法用来读取注解的信息,visitTypeAnnotation 也是用来处理注解信息,但是其用来处理 Type Annotation 注解,Type Annotation 是在JDK以上版本的注解类型。

注解代码:

1
2
3
4
@MyAnnotation(id = 1 , message="message")
public class MyClass implements @MyTypeAnnotation Serializable {

}

ASM 代码:

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
package asm.com.example.annotation;
import java.util.*;
import org.objectweb.asm.*;
public class MyClassDump implements Opcodes {

public static byte[] dump () throws Exception {

ClassWriter cw = new ClassWriter(0);
FieldVisitor fv;
MethodVisitor mv;
AnnotationVisitor av0;

cw.visit(52, ACC_PUBLIC + ACC_SUPER, "com/example/annotation/MyClass", null, "java/lang/Object", new String[] { "java/io/Serializable" });

cw.visitSource("MyClass.java", null);

{
av0 = cw.visitAnnotation("Lcom/example/annotation/MyAnnotation;", true);
av0.visit("id", new Integer(1));
av0.visit("message", "message");
av0.visitEnd();
}
{
av0 = cw.visitTypeAnnotation(268435456, TypePath.fromString("null"), "Lcom/example/annotation/MyTypeAnnotation;", true);
av0.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitLineNumber(6, l0);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
mv.visitInsn(RETURN);
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitLocalVariable("this", "Lcom/example/annotation/MyClass;", null, l0, l1, 0);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
cw.visitEnd();

return cw.toByteArray();
}
}

以下代码为处理 Type Annotation

1
2
av0 = cw.visitTypeAnnotation(268435456, TypePath.fromString("null"), "Lcom/example/annotation/MyTypeAnnotation;", true);
av0.visitEnd();

参考 《Type Annotation》了解Type Annotation 使用。