ASM 操作字节码初探

JVM的类型签名对照表

Type Signature Java Type
Z boolean
B byte
C char
S short
I int
J long
F float
D double
L fully-qualified-class ;fully-qualified-class
[ type type[]
( arg-types ) ret-type method type

比如,java方法是

1
long f (int n, String s, int[] arr);

对应的类型签名就是

1
f (ILjava/lang/String;[I)J

再比如,java方法是

1
private void hi(double a, List<String> b);

那对应的类型签名就是

1
hi (DLjava/util/List;)V

接下来可以利用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
47
public class Test {
public static void main(String[] args) throws Exception {
ClassPrinter printer = new ClassPrinter();
//读取静态内部类Bazhang
ClassReader cr = new ClassReader("Test$Bazhang");
cr.accept(printer, 0);
}
//静态内部类
static class Bazhang {
public Bazhang(int a) {
}
private long f (int n, String s, int[] arr){
return 0;
}
private void hi(double a, List<String> b){
}
}
static class ClassPrinter extends ClassVisitor {
public ClassPrinter() {
super(Opcodes.ASM5);
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
//打印出父类name和本类name
System.out.println(superName + " " + name);
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
//打印出方法名和类型签名
System.out.println(name + " " + desc);
return super.visitMethod(access, name, desc, signature, exceptions);
}
}
}

最后打印出来的内容:

1
2
3
4
java/lang/Object Test$Bazhang
<init> ()V
f (ILjava/lang/String;[I)J
hi (DLjava/util/List;)V

验证了之前的正确性,其中可以看到默认构造函数也打印出来了。

那么接下来干点有意思的事,我们往Bazhang类里新增和方法,就定为:

1
2
3
public void newFunc(String str){
}

这个时候就需要用到ClassWriter了,用于拼接字节码,具体关于ClassReader、ClassVisitor、ClassWriter的文章可以查看这篇http://www.blogjava.net/DLevin/archive/2014/06/25/414292.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void main(String[] args) throws Exception {
ClassReader cr = new ClassReader(Bazhang.class.getName());
ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
cr.accept(cw, Opcodes.ASM5);
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "newFunc", "(Ljava/lang/String;)V", null, null);
mv.visitInsn(Opcodes.RETURN);
mv.visitEnd();
// 获取生成的class文件对应的二进制流
byte[] code = cw.toByteArray();
//将二进制流写到out/下
FileOutputStream fos = new FileOutputStream("out/Bazhang222.class");
fos.write(code);
fos.close();
}

这样就会在out/文件夹下生成Bazhang222.class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
import java.util.List;
class Test$Bazhang {
Test$Bazhang() {
}
private long f(int n, String s, int[] arr) {
return 0L;
}
private void hi(double a, List<String> b) {
}
public void newFunc(String var1) {
}
}

结合之前整理的JVM指令集,使用ASM直接操作字节码也是没问题的,结尾附上ASM源码下载地址:http://forge.ow2.org/projects/asm/