前言:授人以鱼不如授人以渔,应用asm的文章有很多,简单demo的也很多,那么ASM都具备哪些能力呢?如何去学习编写ASM代码呢?什么样的情景需要用到ASM呢?让我们带着这些问题阅读这篇文章吧。
这里由于篇幅限制做了删减(第六部分TreeApi和CoreApi的比较、核心API类的介绍等),如果有兴趣可以联系作者进行交流,
个人认为核心在于第五部分如何查看一个想写的类的ASM代码如何写,以及全面了解ASM都有哪些能力,这样在后面的特定场景下我们才会知道可以通过它来实现想做的功能
一、ASM介绍
1、ASM 是什么
ASM是一个通用的Java字节码操作和分析框架。它可以用于修改现有类或直接以二进制形式动态生成类。ASM提供了一些常见的字节码转换和分析算法,可以从中构建定制的复杂转换和代码分析工具。ASM提供了与其他Java字节码框架类似的功能,但侧重于性能。由于它的设计和实现尽可能小和快,因此非常适合在动态系统中使用(但当然也可以以静态方式使用,例如在编译器中)。
一个.java文件经过Java编译器(javac)编译之后会生成一个.class文件。在.class文件中,存储的是字节码(ByteCode)数据。ASM所操作的对象是字节码(ByteCode),而在许多情况下,字节码(ByteCode)的具体表现形式是.class文件。
ASM处理字节码(ByteCode)的方式是“拆分-修改-合并”。
| 字节码工具 | 类创建 | 实现接口 | 方法调用 | 类扩展 | 父类方法调用 | 优点 | 缺点 | 常见使用 | 学习成本 |
|---|---|---|---|---|---|---|---|---|---|
| java-proxy | 支持 | 支持 | 支持 | 不支持 | 不支持 | 简单动态代理首选 | 功能有限,不支持扩展 | spring-aop,MyBatis | 1星 |
| asm | 支持 | 支持 | 支持 | 支持 | 支持 | 任意字节码插入,几乎不受限制 | 学习难度大,编写代码多 | cglib | 5星 |
| javaassit | 支持 | 支持 | 支持 | 支持 | 支持 | java原始语法,字符串形式插入,写入直观 | 不支持jdk1.5以上的语法,如泛型,增强for | Fastjson,MyBatis | 2星 |
| cglib | 支持 | 支持 | 支持 | 支持 | 支持 | 与bytebuddy看起来差不多 | 正在被bytebuddy淘汰 | EasyMock,jackson-databind | 3星 |
| bytebuddy | 支持 | 支持 | 支持 | 支持 | 支持 | 支持任意维度的拦截,可以获取原始类、方法,以及代理类和全部参数 | 不太直观,学习理解有些成本,API非常多 | SkyWalking,Mockito,Hibernate,powermock | 3星 |
比较表格参考: http://xingyun.jd.com/shendeng/article/detail/7826
- ASM官网:https://asm.ow2.io/
- ASM源码:https://gitlab.ow2.org/asm/asm
- 开发者指南:https://asm.ow2.io/developer-guide.html
2、ASM能做什么
生成、修改、删除(接口、类、字段、方法...)ASM能够对字节码数据进行analyze、generate、transformation,ASM可以形象的理解为“Java语言世界”边缘上一扇大门,通过这扇大门,可以帮助我们进入到“字节码的世界”。
3、ASM实际的使用场景
3.1、Spring当中的ASM
第一个应用场景,是Spring框架当中的AOP。 在很多Java项目中,都会使用到Spring框架,而Spring框架当中的AOP(Aspect Oriented Programming)是依赖于ASM的。具体来说,Spring的AOP,可以通过JDK的动态代理来实现,也可以通过CGLIB实现。其中,CGLib (Code Generation Library)是在ASM的基础上构建起来的,所以,Spring AOP是间接的使用了ASM。(参考自 Spring Framework Reference Documentation的 8.6 Proxying mechanisms)。
3.2、JDK当中的ASM
第二个应用场景,是JDK当中的Lambda表达式。 在Java 8中引入了一个非常重要的特性,就是支持Lambda表达式。Lambda表达式,允许把方法作为参数进行传递,它能够使代码变的更加简洁紧凑。但是,我们可能没有注意到,其实,在现阶段(Java 8版本),Lambda表达式的调用是通过ASM来实现的。
在rt.jar文件的jdk.internal.org.objectweb.asm包当中,就包含了JDK内置的ASM代码。在JDK 8版本当中,它所使用的ASM 5.0版本。
如果我们跟踪Lambda表达式的编码实现,就会找到InnerClassLambdaMetafactory.spinInnerClass()方法。在这个方法当中,我们就会看到:JDK会使用jdk.internal.org.objectweb.asm.ClassWriter来生成一个类,将lambda表达式的代码包装起来。
LambdaMetafactory.metafactory() 第一步,找到这个方法 InnerClassLambdaMetafactory.buildCallSite() 第二步,找到这个方法
InnerClassLambdaMetafactory.spinInnerClass() 第三步,找到这个方法
4、 ASM的两个组成部分
从组成结构上来说,ASM分成两部分,一部分为Core API,另一部分为Tree API。
其中,Core API包括asm.jar、asm-util.jar和asm-commons.jar;其中,Tree API包括asm-tree.jar和asm-analysis.jar。
asm.jar内核心类:ClassReader、ClassVisitor、ClassWriter、FieldVisitor、FieldWriter、MethodVisitor、MethodWriter、Label、Opcodes、Type
ClassReader类,负责读取.class文件里的内容,然后拆分成各个不同的部分。ClassVisitor类,负责对.class文件中某一部分里的信息进行修改。ClassWriter类,负责将各个不同的部分重新组合成一个完整的.class文件。
asm-util.jar内核心类
以Check开头的类,主要负责检查(Check)生成的.class文件内容是否正确。以Trace开头的类,主要负责将.class文件的内容打印成文字输出。根据输出的文字信息,可以探索或追踪(Trace).class文件的内部信息。
5、ClassFile
我们都知道,在.class文件中,存储的是ByteCode数据。但是,这些ByteCode数据并不是杂乱无章的,而是遵循一定的数据结构。
这个.class文件遵循的数据结构就是由 Java Virtual Machine Specification中定义的 The class File Format
6、常见的字节码类库
Apache Commons BCEL:其中BCEL为Byte Code Engineering Library首字母的缩写。
Javassist:Javassist表示Java programming assistant
ObjectWeb ASM:本课程的研究对象。
Byte Buddy:在ASM基础上实现的一个类库。
二、无中生有
1、生成新的接口
预期目标:
生成一个正常接口结构定义的.class文件
1public interface ASMInterface { 2 byte byteType = 1; 3 short shortType = 1; 4 int intType = 1; 5 char charType = 's'; 6 float floatType = 1.1F; 7 double doubleType = 1.2; 8 long longType = 1L; 9 boolean booleanType = false; 10 Byte ByteType = 1; 11 Short ShortType = Short.valueOf((short)1); 12 Integer IntegerType = 1; 13 String StringType = "s"; 14 Float FloatType = 1.1F; 15 Double DoubleType = 1.1; 16 Long LongType = 1L; 17 Boolean BooleanType = true; 18 19 void function(); 20 21 default String defaultFunction(Integer integer) { 22 System.out.println("param = " + integer); 23 return String.valueOf(integer); 24 } 25 26 static Integer getInteger(String str) { 27 return Integer.valueOf(str); 28 } 29}
编码实现:
1public class InterfaceGenerateCore { 2 public static void main(String[] args) throws Exception { 3 String relative_path = "sample/ASMGenerateInterface.class"; 4 String filepath = FileUtils.getFilePath(relative_path); 5 6 // (1) 生成byte[]内容 7 byte[] bytes = dump(); 8 9 // (2) 保存byte[]到文件 10 FileUtils.writeBytes(filepath, bytes); 11 } 12 13 public static byte[] dump() throws Exception { 14 // (1) 创建ClassWriter对象 15 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); 16 17 // (2) 调用visitXxx()方法,调用顺序和说明如下 18 /* 19 * visit 20 * [visitSource][visitModule][visitNestHost][visitPermittedSubclass][visitOuterClass] 21 * (visitAnnotation | 22 * visitTypeAnnotation | 23 * visitAttribute)* 24 * (visitNestMember | 25 * visitInnerClass | 26 * visitRecordComponent | 27 * visitField | 28 * visitMethod)* 29 * visitEnd 30 * []: 表示最多调用一次,可以不调用,但最多调用一次。 31 * ()和|: 表示在多个方法之间,可以选择任意一个,并且多个方法之间不分前后顺序。 32 * *: 表示方法可以调用0次或多次。 33 * */ 34 35 //定义接口 36 /* 37 *visit(version, access, name, signature, superName, interfaces) 38 *version: 表示当前类的版本信息。在下述示例代码中,其取值为Opcodes.V1_8,表示使用Java 8版本。 39 *access: 表示当前类的访问标识(access flag)信息。在下面的示例中,access的取值是ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE,也可以写成ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE。如果想进一步了解这些标识的含义,可以参考Java Virtual Machine Specification的Chapter 4. The class File Format部分。 40 *name: 表示当前类的名字,它采用的格式是Internal Name的形式。在.java文件中,我们使用Java语言来编写代码,使用类名的形式是Fully Qualified Class Name,例如java.lang.String;将.java文件编译之后,就会生成.class文件;在.class文件中,类名的形式会发生变化,称之为Internal Name,例如java/lang/String。因此,将Fully Qualified Class Name转换成Internal Name的方式就是,将.字符转换成/字符。 41 *signature: 表示当前类的泛型信息。因为在这个接口当中不包含任何的泛型信息,因此它的值为null。 42 *superName: 表示当前类的父类信息,它采用的格式是Internal Name的形式。 43 *interfaces: 表示当前类实现了哪些接口信息。 44 **/ 45 cw.visit( 46 V1_8, // version 47 ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, // access 48 "sample/ASMGenerateInterface", // name 49 null, // signature 50 "java/lang/Object", // superName 51 null // interfaces 52 ); 53 //定义字段-基本类型 54 /* 55 * visitField(access, name, descriptor, signature, value) 56 *access参数:表示当前字段或方法带有的访问标识(access flag)信息,例如ACC_PUBLIC、ACC_STATIC和ACC_FINAL等。 57 *name参数:表示当前字段或方法的名字。 58 *descriptor参数:表示当前字段或方法的描述符。这些描述符,与我们平时使用的Java类型是有区别的。byte-B、short-S、int-I、char-C、具体可以参考如下示例代码 59 *signature参数:表示当前字段或方法是否带有泛型信息。换句话说,如果不带有泛型信息,提供一个null就可以了;如果带有泛型信息,就需要给它提供某一个具体的值。 60 *value参数:是visitField()方法的第5个参数。这个参数的取值,与当前字段是否为常量有关系。如果当前字段是一个常量,就需要给value参数提供某一个具体的值;如果当前字段不是常量,那么使用null就可以了。 61 * */ 62 { 63 FieldVisitor fv1 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "byteType", "B", null, new Integer(1)); 64 fv1.visitEnd(); 65 } 66 { 67 FieldVisitor fv2 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "shortType", "S", null, new Integer(1)); 68 fv2.visitEnd(); 69 } 70 { 71 FieldVisitor fv3 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "intType", "I", null, new Integer(1)); 72 fv3.visitEnd(); 73 } 74 { 75 FieldVisitor fv4 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "charType", "C", null, 's'); 76 fv4.visitEnd(); 77 } 78 { 79 FieldVisitor fv5 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "floatType", "F", null, new Float("1.1")); 80 fv5.visitEnd(); 81 } 82 { 83 FieldVisitor fv6 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "doubleType", "D", null, new Double("1.2")); 84 fv6.visitEnd(); 85 } 86 { 87 FieldVisitor fv7 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "longType", "J", null, new Long(1L)); 88 fv7.visitEnd(); 89 } 90 { 91 FieldVisitor fv8 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "booleanType", "Z", null, new Integer(0)); 92 fv8.visitEnd(); 93 } 94 //定义变量-包装类型 95 { 96 FieldVisitor fv11 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "ByteType", "Ljava/lang/Byte;", null, null); 97 fv11.visitEnd(); 98 } 99 { 100 FieldVisitor fv12 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "ShortType", "Ljava/lang/Short;", null,null); 101 fv12.visitEnd(); 102 } 103 { 104 FieldVisitor fv13 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "IntegerType", "Ljava/lang/Integer;", null,null); 105 fv13.visitEnd(); 106 } 107 { 108 FieldVisitor fv14 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "StringType", "Ljava/lang/String;", null, "s"); 109 fv14.visitEnd(); 110 } 111 { 112 FieldVisitor fv15 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "FloatType", "Ljava/lang/Float;", null,null); 113 fv15.visitEnd(); 114 } 115 { 116 FieldVisitor fv16 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "DoubleType", "Ljava/lang/Double;", null,null); 117 fv16.visitEnd(); 118 } 119 { 120 FieldVisitor fv17 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "LongType", "Ljava/lang/Long;", null, null); 121 fv17.visitEnd(); 122 } 123 { 124 FieldVisitor fv18 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "BooleanType", "Ljava/lang/Boolean;", null, null); 125 fv18.visitEnd(); 126 } 127 //定义方法-抽象方法 128 /* 129 * visitMethod(access, name, descriptor, signature, exceptions) 130 *access参数:表示当前字段或方法带有的访问标识(access flag)信息,例如ACC_PUBLIC、ACC_STATIC和ACC_FINAL等。 131 *name参数:表示当前字段或方法的名字。 132 *descriptor参数:表示当前字段或方法的描述符。这些描述符,与我们平时使用的Java类型是有区别的。()内为入参,后面为反参 133 *signature参数:表示当前字段或方法是否带有泛型信息。换句话说,如果不带有泛型信息,提供一个null就可以了;如果带有泛型信息,就需要给它提供某一个具体的值。 134 *exceptions参数:是visitMethod()方法的第5个参数。这个参数的取值,与当前方法声明中是否具有throws XxxException相关。 135 * */ 136 { 137 MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "function", "()V", null, null); 138 mv1.visitEnd(); 139 } 140 //定义方法-默认方法 141 { 142 MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "defaultFunction", "(Ljava/lang/Integer;)Ljava/lang/String;", null, null); 143 mv2.visitCode(); 144 mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 145 mv2.visitTypeInsn(NEW, "java/lang/StringBuilder"); 146 mv2.visitInsn(DUP); 147 mv2.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false); 148 mv2.visitLdcInsn("param = "); 149 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false); 150 mv2.visitVarInsn(ALOAD, 1); 151 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", false); 152 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false); 153 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); 154 mv2.visitVarInsn(ALOAD, 1); 155 mv2.visitMethodInsn(INVOKESTATIC, "java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;", false); 156 mv2.visitInsn(ARETURN); 157 mv2.visitMaxs(3, 2); 158 mv2.visitEnd(); 159 } 160 //定义方法-静态方法 161 { 162 MethodVisitor mv3 = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "getInteger", "(Ljava/lang/String;)Ljava/lang/Integer;", null, null); 163 mv3.visitCode(); 164 mv3.visitVarInsn(ALOAD, 0); 165 mv3.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(Ljava/lang/String;)Ljava/lang/Integer;", false); 166 mv3.visitInsn(ARETURN); 167 mv3.visitMaxs(1, 1); 168 mv3.visitEnd(); 169 } 170 171 { 172 MethodVisitor mv4 = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null); 173 mv4.visitCode(); 174 mv4.visitInsn(ICONST_1); 175 mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false); 176 mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "ByteType", "Ljava/lang/Byte;"); 177 mv4.visitInsn(ICONST_1); 178 mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false); 179 mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "ShortType", "Ljava/lang/Short;"); 180 mv4.visitInsn(ICONST_1); 181 mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false); 182 mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "IntegerType", "Ljava/lang/Integer;"); 183 mv4.visitLdcInsn(new Float("1.1")); 184 mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false); 185 mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "FloatType", "Ljava/lang/Float;"); 186 mv4.visitLdcInsn(new Double("1.1")); 187 mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false); 188 mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "DoubleType", "Ljava/lang/Double;"); 189 mv4.visitInsn(LCONST_1); 190 mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false); 191 mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "LongType", "Ljava/lang/Long;"); 192 mv4.visitInsn(ICONST_1); 193 mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); 194 mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "BooleanType", "Ljava/lang/Boolean;"); 195 mv4.visitInsn(RETURN); 196 mv4.visitMaxs(2, 0); 197 mv4.visitEnd(); 198 } 199 cw.visitEnd(); // 注意,最后要调用visitEnd()方法 200 // (3) 调用toByteArray()方法 201 return cw.toByteArray(); 202 } 203} 204 205
验证结果:
生成的接口是否正确
1public class HelloWorldRun { 2 public static void main(String[] args) throws Exception { 3 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 4 Class<?> clazz = classLoader.loadClass("sample.ASMGenerateInterface"); 5 Field[] declaredFields = clazz.getDeclaredFields(); 6 if (declaredFields.length > 0) { 7 System.out.println("fields:"); 8 for (Field f : declaredFields) { 9 Object value = f.get(null); 10 System.out.println(" " + f.getName() + ": " + value); 11 } 12 } 13 Method[] declaredMethods = clazz.getDeclaredMethods(); 14 if (declaredMethods.length > 0) { 15 System.out.println("methods:"); 16 for (Method m : declaredMethods) { 17 System.out.println(" " + m.getName()); 18 } 19 } 20 } 21}
效果图如下:

2、生成新的类
预期目标:
生成一个正常类结构定义的.class文件
1public class ASMClass { 2 //定义变量-基本类型 3 byte byteType = 1; 4 short shortType = 1; 5 int intType = 1; 6 char charType = 's'; 7 float floatType = 1.1f; 8 double doubleType = 1.2; 9 long longType = 1; 10 boolean booleanType = false; 11 //定义变量-包装类型 12 Byte ByteType = 1; 13 Short ShortType = 1; 14 Integer IntegerType = 1; 15 String StringType = "string"; 16 Float FloatType = 1.1f; 17 Double DoubleType = 1.1; 18 Long LongType = 1l; 19 @Deprecated 20 Boolean BooleanType = true; 21 /* 22 * 静态方法 23 * */ 24 public static Integer getInteger(String str) { 25 return Integer.valueOf(str); 26 } 27 /* 28 * 实例方法 29 * */ 30 public String instanceMethod(Integer integer) { 31 return String.valueOf(integer); 32 } 33} 34 35
编码实现:
1public class ClassGenerateCore { 2 public static void main(String[] args) throws Exception { 3 String relative_path = "sample/ASMGenerateClass.class"; 4 String filepath = FileUtils.getFilePath(relative_path); 5 6 // (1) 生成byte[]内容 7 byte[] bytes = dump(); 8 9 // (2) 保存byte[]到文件 10 FileUtils.writeBytes(filepath, bytes); 11 } 12 13 public static byte[] dump() throws Exception { 14 // (1) 创建ClassWriter对象 15 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); 16 17 // (2) 调用visitXxx()方法,调用顺序和说明如下 18 /* 19 * visit 20 * [visitSource][visitModule][visitNestHost][visitPermittedSubclass][visitOuterClass] 21 * (visitAnnotation | 22 * visitTypeAnnotation | 23 * visitAttribute)* 24 * (visitNestMember | 25 * visitInnerClass | 26 * visitRecordComponent | 27 * visitField | 28 * visitMethod)* 29 * visitEnd 30 * []: 表示最多调用一次,可以不调用,但最多调用一次。 31 * ()和|: 表示在多个方法之间,可以选择任意一个,并且多个方法之间不分前后顺序。 32 * *: 表示方法可以调用0次或多次。 33 * */ 34 35 //定义接口 36 /* 37 *visit(version, access, name, signature, superName, interfaces) 38 *version: 表示当前类的版本信息。在下述示例代码中,其取值为Opcodes.V1_8,表示使用Java 8版本。 39 *access: 表示当前类的访问标识(access flag)信息。在下面的示例中,access的取值是ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE,也可以写成ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE。如果想进一步了解这些标识的含义,可以参考Java Virtual Machine Specification的Chapter 4. The class File Format部分。 40 *name: 表示当前类的名字,它采用的格式是Internal Name的形式。在.java文件中,我们使用Java语言来编写代码,使用类名的形式是Fully Qualified Class Name,例如java.lang.String;将.java文件编译之后,就会生成.class文件;在.class文件中,类名的形式会发生变化,称之为Internal Name,例如java/lang/String。因此,将Fully Qualified Class Name转换成Internal Name的方式就是,将.字符转换成/字符。 41 *signature: 表示当前类的泛型信息。因为在这个接口当中不包含任何的泛型信息,因此它的值为null。 42 *superName: 表示当前类的父类信息,它采用的格式是Internal Name的形式。 43 *interfaces: 表示当前类实现了哪些接口信息。 44 **/ 45 cw.visit( 46 V1_8, // version 47 ACC_PUBLIC + ACC_SUPER, // access 48 "sample/ASMGenerateClass", // name 49 null, // signature 50 "java/lang/Object", // superName 51 null // interfaces 52 ); 53 //定义字段-基本类型 54 /* 55 * visitField(access, name, descriptor, signature, value) 56 *access参数:表示当前字段或方法带有的访问标识(access flag)信息,例如ACC_PUBLIC、ACC_STATIC和ACC_FINAL等。 57 *name参数:表示当前字段或方法的名字。 58 *descriptor参数:表示当前字段或方法的描述符。这些描述符,与我们平时使用的Java类型是有区别的。byte-B、short-S、int-I、char-C、具体可以参考如下示例代码 59 *signature参数:表示当前字段或方法是否带有泛型信息。换句话说,如果不带有泛型信息,提供一个null就可以了;如果带有泛型信息,就需要给它提供某一个具体的值。 60 *value参数:是visitField()方法的第5个参数。这个参数的取值,与当前字段是否为常量有关系。如果当前字段是一个常量,就需要给value参数提供某一个具体的值;如果当前字段不是常量,那么使用null就可以了。 61 * */ 62 { 63 FieldVisitor fv1 = cw.visitField(0, "byteType", "B", null, new Byte("1")); 64 fv1.visitEnd(); 65 } 66 { 67 FieldVisitor fv2 = cw.visitField(0, "shortType", "S", null, new Short("1")); 68 fv2.visitEnd(); 69 } 70 { 71 FieldVisitor fv3 = cw.visitField(0, "intType", "I", null, new Integer(1)); 72 fv3.visitEnd(); 73 } 74 { 75 FieldVisitor fv4 = cw.visitField(0, "charType", "C", null, "s"); 76 fv4.visitEnd(); 77 } 78 { 79 FieldVisitor fv5 = cw.visitField(0, "floatType", "F", null, new Float("1.1")); 80 fv5.visitEnd(); 81 } 82 { 83 FieldVisitor fv6 = cw.visitField(0, "doubleType", "D", null, new Double("1.2")); 84 fv6.visitEnd(); 85 } 86 { 87 FieldVisitor fv7 = cw.visitField(0, "longType", "J", null, new Long(1)); 88 fv7.visitEnd(); 89 } 90 { 91 FieldVisitor fv8 = cw.visitField(0, "booleanType", "Z", null, false); 92 fv8.visitEnd(); 93 } 94 //定义变量-包装类型 95 { 96 FieldVisitor fv11 = cw.visitField(0, "ByteType", "Ljava/lang/Byte;", null, 1); 97 fv11.visitEnd(); 98 } 99 { 100 FieldVisitor fv12 = cw.visitField(0, "ShortType", "Ljava/lang/Short;", null, 1); 101 fv12.visitEnd(); 102 } 103 { 104 FieldVisitor fv13 = cw.visitField(0, "IntegerType", "Ljava/lang/Integer;", null, 1); 105 fv13.visitEnd(); 106 } 107 { 108 FieldVisitor fv14 = cw.visitField(0, "StringType", "Ljava/lang/String;", null, "s"); 109 fv14.visitEnd(); 110 } 111 { 112 FieldVisitor fv15 = cw.visitField(0, "FloatType", "Ljava/lang/Float;", null, 1.1f); 113 fv15.visitEnd(); 114 } 115 { 116 FieldVisitor fv16 = cw.visitField(ACC_PUBLIC, "DoubleType", "Ljava/lang/Double;", null, 1.1); 117 fv16.visitEnd(); 118 } 119 { 120 FieldVisitor fv17 = cw.visitField(0, "LongType", "Ljava/lang/Long;", null, 1l); 121 fv17.visitEnd(); 122 } 123 { 124 FieldVisitor fv18 = cw.visitField(ACC_DEPRECATED, "BooleanType", "Ljava/lang/Boolean;", null, true); 125 { 126 AnnotationVisitor annotationVisitor0 = fv18.visitAnnotation("Ljava/lang/Deprecated;", true); 127 annotationVisitor0.visitEnd(); 128 } 129 fv18.visitEnd(); 130 } 131 /* 132 * visitMethod(access, name, descriptor, signature, exceptions) 133 *access参数:表示当前字段或方法带有的访问标识(access flag)信息,例如ACC_PUBLIC、ACC_STATIC和ACC_FINAL等。 134 *name参数:表示当前字段或方法的名字。 135 *descriptor参数:表示当前字段或方法的描述符。这些描述符,与我们平时使用的Java类型是有区别的。()内为入参,后面为反参 136 *signature参数:表示当前字段或方法是否带有泛型信息。换句话说,如果不带有泛型信息,提供一个null就可以了;如果带有泛型信息,就需要给它提供某一个具体的值。 137 *exceptions参数:是visitMethod()方法的第5个参数。这个参数的取值,与当前方法声明中是否具有throws XxxException相关。 138 * */ 139 //定义方法-静态代码块 140 { 141 MethodVisitor mv2 = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null); 142 mv2.visitCode(); 143 mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 144 mv2.visitLdcInsn("class initialization method"); 145 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); 146 mv2.visitInsn(RETURN); 147 mv2.visitMaxs(2, 0); 148 mv2.visitEnd(); 149 } 150 //定义方法-无参构造器 151 { 152 MethodVisitor methodVisitor = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); 153 methodVisitor.visitCode(); 154 methodVisitor.visitVarInsn(ALOAD, 0); 155 methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); 156 methodVisitor.visitVarInsn(ALOAD, 0); 157 methodVisitor.visitInsn(ICONST_1); 158 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "byteType", "B"); 159 methodVisitor.visitVarInsn(ALOAD, 0); 160 methodVisitor.visitInsn(ICONST_1); 161 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "shortType", "S"); 162 methodVisitor.visitVarInsn(ALOAD, 0); 163 methodVisitor.visitInsn(ICONST_1); 164 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "intType", "I"); 165 methodVisitor.visitVarInsn(ALOAD, 0); 166 methodVisitor.visitIntInsn(BIPUSH, 115); 167 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "charType", "C"); 168 methodVisitor.visitVarInsn(ALOAD, 0); 169 methodVisitor.visitLdcInsn(new Float("1.1")); 170 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "floatType", "F"); 171 methodVisitor.visitVarInsn(ALOAD, 0); 172 methodVisitor.visitLdcInsn(new Double("1.2")); 173 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "doubleType", "D"); 174 methodVisitor.visitVarInsn(ALOAD, 0); 175 methodVisitor.visitInsn(LCONST_1); 176 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "longType", "J"); 177 methodVisitor.visitVarInsn(ALOAD, 0); 178 methodVisitor.visitInsn(ICONST_0); 179 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "booleanType", "Z"); 180 methodVisitor.visitVarInsn(ALOAD, 0); 181 methodVisitor.visitInsn(ICONST_1); 182 methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false); 183 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "ByteType", "Ljava/lang/Byte;"); 184 methodVisitor.visitVarInsn(ALOAD, 0); 185 methodVisitor.visitInsn(ICONST_1); 186 methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false); 187 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "ShortType", "Ljava/lang/Short;"); 188 methodVisitor.visitVarInsn(ALOAD, 0); 189 methodVisitor.visitInsn(ICONST_1); 190 methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false); 191 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "IntegerType", "Ljava/lang/Integer;"); 192 methodVisitor.visitVarInsn(ALOAD, 0); 193 methodVisitor.visitLdcInsn("string"); 194 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "StringType", "Ljava/lang/String;"); 195 methodVisitor.visitVarInsn(ALOAD, 0); 196 methodVisitor.visitLdcInsn(new Float("1.1")); 197 methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false); 198 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "FloatType", "Ljava/lang/Float;"); 199 methodVisitor.visitVarInsn(ALOAD, 0); 200 methodVisitor.visitLdcInsn(new Double("1.1")); 201 methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false); 202 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "DoubleType", "Ljava/lang/Double;"); 203 methodVisitor.visitVarInsn(ALOAD, 0); 204 methodVisitor.visitInsn(LCONST_1); 205 methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false); 206 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "LongType", "Ljava/lang/Long;"); 207 methodVisitor.visitVarInsn(ALOAD, 0); 208 methodVisitor.visitInsn(ICONST_1); 209 methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); 210 methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "BooleanType", "Ljava/lang/Boolean;"); 211 methodVisitor.visitInsn(RETURN); 212 methodVisitor.visitMaxs(3, 1); 213 methodVisitor.visitEnd(); 214 215 } 216 //定义方法-静态方法 217 { 218 MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "getInteger", "(Ljava/lang/String;)Ljava/lang/Integer;", null, null); 219 mv1.visitCode(); 220 mv1.visitVarInsn(ALOAD, 0); 221 mv1.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(Ljava/lang/String;)Ljava/lang/Integer;", false); 222 mv1.visitInsn(ARETURN); 223 mv1.visitMaxs(1, 1); 224 mv1.visitEnd(); 225 } 226 //定义方法-实例方法 227 { 228 MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "instanceMethod", "(Ljava/lang/Integer;)Ljava/lang/String;", null, null); 229 mv2.visitCode(); 230 mv2.visitVarInsn(ALOAD, 1); 231 mv2.visitMethodInsn(INVOKESTATIC, "java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;", false); 232 mv2.visitInsn(ARETURN); 233 mv2.visitMaxs(1, 2); 234 mv2.visitEnd(); 235 } 236 237 cw.visitEnd(); // 注意,最后要调用visitEnd()方法 238 // (3) 调用toByteArray()方法 239 return cw.toByteArray(); 240 } 241}
验证结果:
1public class HelloWorldRun { 2 public static void main(String[] args) throws Exception { 3 Class<?> clazz = Class.forName("sample.ASMGenerateClass"); 4 Method method = clazz.getDeclaredMethod("instanceMethod",Integer.class); 5 Object instance = clazz.newInstance(); 6 Object invoke = method.invoke(instance, new Integer(12)); 7 Class<?> aClass = invoke.getClass(); 8 System.out.println("aClass = " + aClass); 9 } 10} 11或者 12public class HelloWorldRun { 13 public static void main(String[] args) throws Exception { 14 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 15 Class<?> clazz = classLoader.loadClass("sample.ASMGenerateClass"); 16 Field[] declaredFields = clazz.getDeclaredFields(); 17 if (declaredFields.length > 0) { 18 for (Field f : declaredFields) { 19 Object value = f.get(null); 20 System.out.println(" " + f.getName() + ": " + value); 21 } 22 } 23 Method[] declaredMethods = clazz.getDeclaredMethods(); 24 if (declaredMethods.length > 0) { 25 for (Method m : declaredMethods) { 26 System.out.println(" " + m.getName()); 27 } 28 } 29 } 30}
效果图如下:

ClassVisitor中visitXxx()的调用顺序
1visit 2[visitSource][visitModule][visitNestHost][visitPermittedSubclass][visitOuterClass] 3( 4 visitAnnotation | 5 visitTypeAnnotation | 6 visitAttribute 7)* 8( 9 visitNestMember | 10 visitInnerClass | 11 visitRecordComponent | 12 visitField | 13 visitMethod 14)* 15visitEnd 16其中,涉及到一些符号,它们的含义如下: 17[]: 表示最多调用一次,可以不调用,但最多调用一次。 18()和|: 表示在多个方法之间,可以选择任意一个,并且多个方法之间不分前后顺序。 19*: 表示方法可以调用0次或多次。
FieldVisitor中visitXxx()的调用顺序
1( 2 visitAnnotation | 3 visitTypeAnnotation | 4 visitAttribute 5)* 6visitEnd
MethodVisitor中visitXxx()的调用顺序
1(visitParameter)* 2[visitAnnotationDefault] 3(visitAnnotation | visitAnnotableParameterCount | visitParameterAnnotation | visitTypeAnnotation | visitAttribute)* 4[ 5 visitCode 6 ( 7 visitFrame | 8 visitXxxInsn | 9 visitLabel | 10 visitInsnAnnotation | 11 visitTryCatchBlock | 12 visitTryCatchAnnotation | 13 visitLocalVariable | 14 visitLocalVariableAnnotation | 15 visitLineNumber 16 )* 17 visitMaxs 18] 19visitEnd 20第一组,在visitCode()方法之前的方法。这一组的方法,主要负责parameter、annotation和attributes等内容 21第二组,在visitCode()方法和visitMaxs()方法之间的方法。这一组的方法,主要负责当前方法的“方法体”内的opcode内容。其中,visitCode()方法,标志着方法体的开始,而visitMaxs()方法,标志着方法体的结束。 22第三组,是visitEnd()方法。这个visitEnd()方法,是最后一个进行调用的方法。
不同的MethodVisitor对象,它们的visitXxx()方法是彼此独立的,只要各自遵循方法的调用顺序,就能够得到正确的结果。
三、狸猫换太子
1、修改类的版本
ClassVisitor子类实现
1public class ClassChangeVersionVisitor extends ClassVisitor { 2 public ClassChangeVersionVisitor(int api, ClassVisitor classVisitor) { 3 super(api, classVisitor); 4 } 5 6 @Override 7 public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { 8 super.visit(Opcodes.V1_7, access, name, signature, superName, interfaces); 9 } 10}
使用ClassVisitor的子类ClassChangeVersionVisitor进行类的版本修改
1public class ASMModifyClass { 2 public static void main(String[] args) throws Exception { 3 String relative_path = "sample/HelloWorld.class"; 4 String filepath = FileUtils.getFilePath(relative_path); 5 byte[] bytes = FileUtils.readBytes(filepath); 6 7 //(1)构建ClassReader 8 ClassReader cr = new ClassReader(bytes); 9 10 //(2)构建ClassWriter 11 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); 12 13 //(3)串连ClassVisitor 14 int api = Opcodes.ASM9; 15 ClassVisitor cv = new ClassChangeVersionVisitor(api, cw); 16 17 //(4)结合ClassReader和ClassVisitor 18 int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES; 19 cr.accept(cv, parsingOptions); 20 21 //(5)生成byte[] 22 byte[] bytes2 = cw.toByteArray(); 23 24 FileUtils.writeBytes(filepath, bytes2); 25 } 26}
验证&效果
通过javap -p -v HelloWorld命令可以看到版本号信息已从52调整位51

2.给每个方法添加计算调用时间
对目标类进行方法改造调换---为每个方法添加用时计算
1 2public class HelloWorld { 3 public int add(int a, int b) throws InterruptedException { 4 int c = a + b; 5 Random rand = new Random(System.currentTimeMillis()); 6 int num = rand.nextInt(300); 7 Thread.sleep(100 + num); 8 return c; 9 } 10 11 public int sub(int a, int b) throws InterruptedException { 12 int c = a - b; 13 Random rand = new Random(System.currentTimeMillis()); 14 int num = rand.nextInt(400); 15 Thread.sleep(100 + num); 16 return c; 17 } 18}
ASM编码实现
1 2public class MethodTimerVisitor2 extends ClassVisitor { 3 private String owner; 4 private boolean isInterface; 5 6 public MethodTimerVisitor2(int api, ClassVisitor classVisitor) { 7 super(api, classVisitor); 8 } 9 10 @Override 11 public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { 12 super.visit(version, access, name, signature, superName, interfaces); 13 owner = name; 14 isInterface = (access & ACC_INTERFACE) != 0; 15 } 16 17 @Override 18 public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { 19 MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions); 20 if (!isInterface && mv != null && !"<init>".equals(name) && !"<clinit>".equals(name)) { 21 boolean isAbstractMethod = (access & ACC_ABSTRACT) != 0; 22 boolean isNativeMethod = (access & ACC_NATIVE) != 0; 23 if (!isAbstractMethod && !isNativeMethod) { 24 // 每遇到一个合适的方法,就添加一个相应的字段 25 FieldVisitor fv = super.visitField(ACC_PUBLIC | ACC_STATIC, getFieldName(name), "J", null, null); 26 if (fv != null) { 27 fv.visitEnd(); 28 } 29 30 mv = new MethodTimerAdapter2(api, mv, owner, name); 31 } 32 33 } 34 return mv; 35 } 36 37 38 private String getFieldName(String methodName) { 39 return "timer_" + methodName; 40 } 41 42 private class MethodTimerAdapter2 extends MethodVisitor { 43 private final String owner; 44 private final String methodName; 45 46 public MethodTimerAdapter2(int api, MethodVisitor mv, String owner, String methodName) { 47 super(api, mv); 48 this.owner = owner; 49 this.methodName = methodName; 50 } 51 52 @Override 53 public void visitCode() { 54 // 首先,处理自己的代码逻辑 55 super.visitFieldInsn(GETSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应 56 super.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false); 57 super.visitInsn(LSUB); 58 super.visitFieldInsn(PUTSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应 59 60 // 其次,调用父类的方法实现 61 super.visitCode(); 62 } 63 64 @Override 65 public void visitInsn(int opcode) { 66 // 首先,处理自己的代码逻辑 67 if ((opcode >= IRETURN && opcode <= RETURN) || opcode == ATHROW) { 68 super.visitFieldInsn(GETSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应 69 super.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false); 70 super.visitInsn(LADD); 71 super.visitFieldInsn(PUTSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应 72 } 73 74 // 其次,调用父类的方法实现 75 super.visitInsn(opcode); 76 } 77 } 78}
对方法进行转换
1 2public class HelloWorldTransformCore { 3 private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; 4 5 public static void main(String[] args) { 6 String relative_path = "sample/HelloWorld.class"; 7 String dir = HelloWorldTransformCore.class.getResource("/").getPath(); 8 String filepath = dir + relative_path; 9 File file = new File(filepath); 10 try { 11 InputStream in = new FileInputStream(file); 12 in = new BufferedInputStream(in); 13 ByteArrayOutputStream bao = new ByteArrayOutputStream(); 14 copyLarge(in, bao, new byte[DEFAULT_BUFFER_SIZE]); 15 byte[] bytes1 = bao.toByteArray(); 16 17 //(1)构建ClassReader 18 ClassReader cr = new ClassReader(bytes1); 19 20 //(2)构建ClassWriter 21 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); 22 23 //(3)串连ClassVisitor 24 int api = Opcodes.ASM9; 25 ClassVisitor cv = new MethodTimerVisitor2(api, cw); 26 27 //(4)结合ClassReader和ClassVisitor 28 int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES; 29 cr.accept(cv, parsingOptions); 30 31 //(5)生成byte[] 32 byte[] bytes2 = cw.toByteArray(); 33 OutputStream out = new FileOutputStream(filepath); 34 BufferedOutputStream buff = new BufferedOutputStream(out); 35 buff.write(bytes2); 36 buff.flush(); 37 buff.close(); 38 System.out.println("file://" + filepath); 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } 42 } 43 44 public static long copyLarge(final InputStream input, final OutputStream output, final byte[] buffer) 45 throws IOException { 46 long count = 0; 47 int n; 48 while (-1 != (n = input.read(buffer))) { 49 output.write(buffer, 0, n); 50 count += n; 51 } 52 return count; 53 } 54}
验证结果
1public class HelloWorldRun { 2 public static void main(String[] args) throws Exception { 3 // 第一部分,先让“子弹飞一会儿”,让程序运行一段时间 4 HelloWorld instance = new HelloWorld(); 5 Random rand = new Random(System.currentTimeMillis()); 6 for (int i = 0; i < 10; i++) { 7 boolean flag = rand.nextBoolean(); 8 int a = rand.nextInt(50); 9 int b = rand.nextInt(50); 10 if (flag) { 11 int c = instance.add(a, b); 12 String line = String.format("%d + %d = %d", a, b, c); 13 System.out.println(line); 14 } 15 else { 16 int c = instance.sub(a, b); 17 String line = String.format("%d - %d = %d", a, b, c); 18 System.out.println(line); 19 } 20 } 21 22 // 第二部分,来查看方法运行的时间 23 Class<?> clazz = HelloWorld.class; 24 Field[] declaredFields = clazz.getDeclaredFields(); 25 for (Field f : declaredFields) { 26 String fieldName = f.getName(); 27 f.setAccessible(true); 28 if (fieldName.startsWith("timer")) { 29 Object FieldValue = f.get(null); 30 System.out.println(fieldName + " = " + FieldValue); 31 } 32 } 33 } 34}
3、打印方法参数和返回值
对目标类进行方法改造---为每个方法添加打印入参和出参
1public class HelloWorld { 2 public int test(String name, int age, long idCard, Object obj) { 3 int hashCode = 0; 4 hashCode += name.hashCode(); 5 hashCode += age; 6 hashCode += (int) (idCard % Integer.MAX_VALUE); 7 hashCode += obj.hashCode(); 8 return hashCode; 9 } 10}
我们想实现的预期目标:打印出“方法接收的参数值”和“方法的返回值”。
1public class HelloWorld { 2 public int test(String name, int age, long idCard, Object obj) { 3 4 int hashCode = 0; 5 hashCode += name.hashCode(); 6 hashCode += age; 7 hashCode += (int) (idCard % Integer.MAX_VALUE); 8 hashCode += obj.hashCode(); 9 System.out.println(hashCode); 10 return hashCode; 11 } 12}
实现这个功能的思路:在“方法进入”的时候,打印出“方法接收的参数值”;在“方法退出”的时候,打印出“方法的返回值”。
首先,我们添加一个ParameterUtils类,在这个类定义了许多print方法,这些print方法可以打印不同类型的数据。
1public class ParameterUtils { 2 private static final DateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 3 4 public static void printValueOnStack(boolean value) { 5 System.out.println(" " + value); 6 } 7 8 public static void printValueOnStack(byte value) { 9 System.out.println(" " + value); 10 } 11 12 public static void printValueOnStack(char value) { 13 System.out.println(" " + value); 14 } 15 16 public static void printValueOnStack(short value) { 17 System.out.println(" " + value); 18 } 19 20 public static void printValueOnStack(int value) { 21 System.out.println(" " + value); 22 } 23 24 public static void printValueOnStack(float value) { 25 System.out.println(" " + value); 26 } 27 28 public static void printValueOnStack(long value) { 29 System.out.println(" " + value); 30 } 31 32 public static void printValueOnStack(double value) { 33 System.out.println(" " + value); 34 } 35 36 public static void printValueOnStack(Object value) { 37 if (value == null) { 38 System.out.println(" " + value); 39 } 40 else if (value instanceof String) { 41 System.out.println(" " + value); 42 } 43 else if (value instanceof Date) { 44 System.out.println(" " + fm.format(value)); 45 } 46 else if (value instanceof char[]) { 47 System.out.println(" " + Arrays.toString((char[])value)); 48 } 49 else { 50 System.out.println(" " + value.getClass() + ": " + value.toString()); 51 } 52 } 53 54 public static void printText(String str) { 55 System.out.println(str); 56 } 57}
在下面的MethodParameterVisitor2类当中,我们将使用ParameterUtils类帮助我们打印信息。
ASM编码实现
1 2public class MethodParameterVisitor2 extends ClassVisitor { 3 public MethodParameterVisitor2(int api, ClassVisitor classVisitor) { 4 super(api, classVisitor); 5 } 6 7 @Override 8 public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { 9 MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions); 10 if (mv != null && !name.equals("<init>")) { 11 boolean isAbstractMethod = (access & ACC_ABSTRACT) != 0; 12 boolean isNativeMethod = (access & ACC_NATIVE) != 0; 13 if (!isAbstractMethod && !isNativeMethod) { 14 mv = new MethodParameterAdapter2(api, mv, access, name, descriptor); 15 } 16 } 17 return mv; 18 } 19 20 private static class MethodParameterAdapter2 extends MethodVisitor { 21 private final int methodAccess; 22 private final String methodName; 23 private final String methodDesc; 24 25 public MethodParameterAdapter2(int api, MethodVisitor mv, int methodAccess, String methodName, String methodDesc) { 26 super(api, mv); 27 this.methodAccess = methodAccess; 28 this.methodName = methodName; 29 this.methodDesc = methodDesc; 30 } 31 32 @Override 33 public void visitCode() { 34 // 首先,处理自己的代码逻辑 35 boolean isStatic = ((methodAccess & ACC_STATIC) != 0); 36 int slotIndex = isStatic ? 0 : 1; 37 38 printMessage("Method Enter: " + methodName + methodDesc); 39 40 Type methodType = Type.getMethodType(methodDesc); 41 Type[] argumentTypes = methodType.getArgumentTypes(); 42 for (Type t : argumentTypes) { 43 int sort = t.getSort(); 44 int size = t.getSize(); 45 String descriptor = t.getDescriptor(); 46 int opcode = t.getOpcode(ILOAD); 47 super.visitVarInsn(opcode, slotIndex); 48 if (sort >= Type.BOOLEAN && sort <= Type.DOUBLE) { 49 String methodDesc = String.format("(%s)V", descriptor); 50 printValueOnStack(methodDesc); 51 } 52 else { 53 printValueOnStack("(Ljava/lang/Object;)V"); 54 } 55 56 slotIndex += size; 57 } 58 59 // 其次,调用父类的方法实现 60 super.visitCode(); 61 } 62 63 @Override 64 public void visitInsn(int opcode) { 65 // 首先,处理自己的代码逻辑 66 if ((opcode >= IRETURN && opcode <= RETURN) || opcode == ATHROW) { 67 printMessage("Method Exit: " + methodName + methodDesc); 68 if (opcode >= IRETURN && opcode <= DRETURN) { 69 Type methodType = Type.getMethodType(methodDesc); 70 Type returnType = methodType.getReturnType(); 71 int size = returnType.getSize(); 72 String descriptor = returnType.getDescriptor(); 73 74 if (size == 1) { 75 super.visitInsn(DUP); 76 } 77 else { 78 super.visitInsn(DUP2); 79 } 80 String methodDesc = String.format("(%s)V", descriptor); 81 printValueOnStack(methodDesc); 82 } 83 else if (opcode == ARETURN) { 84 super.visitInsn(DUP); 85 printValueOnStack("(Ljava/lang/Object;)V"); 86 } 87 else if (opcode == RETURN) { 88 printMessage(" return void"); 89 } 90 else { 91 printMessage(" abnormal return"); 92 } 93 } 94 95 // 其次,调用父类的方法实现 96 super.visitInsn(opcode); 97 } 98 99 private void printMessage(String str) { 100 super.visitLdcInsn(str); 101 super.visitMethodInsn(INVOKESTATIC, "sample/ParameterUtils", "printText", "(Ljava/lang/String;)V", false); 102 } 103 104 private void printValueOnStack(String descriptor) { 105 super.visitMethodInsn(INVOKESTATIC, "sample/ParameterUtils", "printValueOnStack", descriptor, false); 106 } 107 } 108}
进行转换
1 2public class HelloWorldTransformCore { 3 public static void main(String[] args) { 4 String relative_path = "sample/HelloWorld.class"; 5 String filepath = FileUtils.getFilePath(relative_path); 6 byte[] bytes1 = FileUtils.readBytes(filepath); 7 8 //(1)构建ClassReader 9 ClassReader cr = new ClassReader(bytes1); 10 11 //(2)构建ClassWriter 12 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); 13 14 //(3)串连ClassVisitor 15 int api = Opcodes.ASM9; 16 ClassVisitor cv = new MethodParameterVisitor2(api, cw); 17 18 //(4)结合ClassReader和ClassVisitor 19 int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES; 20 cr.accept(cv, parsingOptions); 21 22 //(5)生成byte[] 23 byte[] bytes2 = cw.toByteArray(); 24 25 FileUtils.writeBytes(filepath, bytes2); 26 } 27}
验证结果
1public class HelloWorldRun { 2 public static void main(String[] args) throws Exception { 3 HelloWorld instance = new HelloWorld(); 4 int hashCode = instance.test("Tomcat", 10, System.currentTimeMillis(), new Object()); 5 int remainder = hashCode % 2; 6 7 if (remainder == 0) { 8 System.out.println("hashCode is even number."); 9 } 10 else { 11 System.out.println("hashCode is odd number."); 12 } 13 } 14}
四、非顺序结构
1、if语句
1public class HelloWorld { 2 public void test(int value) { 3 if (value == 0) { 4 System.out.println("value is 0"); 5 } 6 else { 7 System.out.println("value is not 0"); 8 } 9 } 10}
ASM编码实现
1 2public class HelloWorldGenerateCore { 3 public static void main(String[] args) throws Exception { 4 String relative_path = "sample/HelloWorld.class"; 5 String filepath = FileUtils.getFilePath(relative_path); 6 7 // (1) 生成byte[]内容 8 byte[] bytes = dump(); 9 10 // (2) 保存byte[]到文件 11 FileUtils.writeBytes(filepath, bytes); 12 } 13 14 public static byte[] dump() throws Exception { 15 // (1) 创建ClassWriter对象 16 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); 17 18 // (2) 调用visitXxx()方法 19 cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, "sample/HelloWorld", 20 null, "java/lang/Object", null); 21 22 { 23 MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); 24 mv1.visitCode(); 25 mv1.visitVarInsn(ALOAD, 0); 26 mv1.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); 27 mv1.visitInsn(RETURN); 28 mv1.visitMaxs(0, 0); 29 mv1.visitEnd(); 30 } 31 32 { 33 MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "test", "(I)V", null, null); 34 Label elseLabel = new Label(); 35 Label returnLabel = new Label(); 36 37 // 第1段 38 mv2.visitCode(); 39 mv2.visitVarInsn(ILOAD, 1); 40 mv2.visitJumpInsn(IFNE, elseLabel); 41 mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 42 mv2.visitLdcInsn("value is 0"); 43 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); 44 mv2.visitJumpInsn(GOTO, returnLabel); 45 46 // 第2段 47 mv2.visitLabel(elseLabel); 48 mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 49 mv2.visitLdcInsn("value is not 0"); 50 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); 51 52 // 第3段 53 mv2.visitLabel(returnLabel); 54 mv2.visitInsn(RETURN); 55 mv2.visitMaxs(0, 0); 56 mv2.visitEnd(); 57 } 58 59 cw.visitEnd(); 60 61 // (3) 调用toByteArray()方法 62 return cw.toByteArray(); 63 } 64}
验证结果
1 2public class HelloWorldRun { 3 public static void main(String[] args) throws Exception { 4 Class<?> clazz = Class.forName("sample.HelloWorld"); 5 Object obj = clazz.newInstance(); 6 7 Method method = clazz.getDeclaredMethod("test", int.class); 8 method.invoke(obj, 0); 9 method.invoke(obj, 1); 10 } 11}
2、switch语句
1public class HelloWorld { 2 public void test(int val) { 3 switch (val) { 4 case 1: 5 System.out.println("val = 1"); 6 break; 7 case 2: 8 System.out.println("val = 2"); 9 break; 10 case 3: 11 System.out.println("val = 3"); 12 break; 13 case 4: 14 System.out.println("val = 4"); 15 break; 16 default: 17 System.out.println("val is unknown"); 18 } 19 } 20}
ASM编码实现
1 2public class HelloWorldGenerateCore { 3 public static void main(String[] args) throws Exception { 4 String relative_path = "sample/HelloWorld.class"; 5 String filepath = FileUtils.getFilePath(relative_path); 6 7 // (1) 生成byte[]内容 8 byte[] bytes = dump(); 9 10 // (2) 保存byte[]到文件 11 FileUtils.writeBytes(filepath, bytes); 12 } 13 14 public static byte[] dump() throws Exception { 15 // (1) 创建ClassWriter对象 16 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); 17 18 // (2) 调用visitXxx()方法 19 cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, "sample/HelloWorld", 20 null, "java/lang/Object", null); 21 22 { 23 MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); 24 mv1.visitCode(); 25 mv1.visitVarInsn(ALOAD, 0); 26 mv1.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); 27 mv1.visitInsn(RETURN); 28 mv1.visitMaxs(0, 0); 29 mv1.visitEnd(); 30 } 31 32 { 33 MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "test", "(I)V", null, null); 34 Label caseLabel1 = new Label(); 35 Label caseLabel2 = new Label(); 36 Label caseLabel3 = new Label(); 37 Label caseLabel4 = new Label(); 38 Label defaultLabel = new Label(); 39 Label returnLabel = new Label(); 40 41 // 第1段 42 mv2.visitCode(); 43 mv2.visitVarInsn(ILOAD, 1); 44 mv2.visitTableSwitchInsn(1, 4, defaultLabel, new Label[]{caseLabel1, caseLabel2, caseLabel3, caseLabel4}); 45 46 // 第2段 47 mv2.visitLabel(caseLabel1); 48 mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 49 mv2.visitLdcInsn("val = 1"); 50 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); 51 mv2.visitJumpInsn(GOTO, returnLabel); 52 53 // 第3段 54 mv2.visitLabel(caseLabel2); 55 mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 56 mv2.visitLdcInsn("val = 2"); 57 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); 58 mv2.visitJumpInsn(GOTO, returnLabel); 59 60 // 第4段 61 mv2.visitLabel(caseLabel3); 62 mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 63 mv2.visitLdcInsn("val = 3"); 64 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); 65 mv2.visitJumpInsn(GOTO, returnLabel); 66 67 // 第5段 68 mv2.visitLabel(caseLabel4); 69 mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 70 mv2.visitLdcInsn("val = 4"); 71 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); 72 mv2.visitJumpInsn(GOTO, returnLabel); 73 74 // 第6段 75 mv2.visitLabel(defaultLabel); 76 mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 77 mv2.visitLdcInsn("val is unknown"); 78 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); 79 80 // 第7段 81 mv2.visitLabel(returnLabel); 82 mv2.visitInsn(RETURN); 83 mv2.visitMaxs(0, 0); 84 mv2.visitEnd(); 85 } 86 87 cw.visitEnd(); 88 89 // (3) 调用toByteArray()方法 90 return cw.toByteArray(); 91 } 92}
验证结果
1import java.lang.reflect.Method; 2 3public class HelloWorldRun { 4 public static void main(String[] args) throws Exception { 5 Class<?> clazz = Class.forName("sample.HelloWorld"); 6 Object obj = clazz.newInstance(); 7 8 Method method = clazz.getDeclaredMethod("test", int.class); 9 for (int i = 1; i < 6; i++) { 10 method.invoke(obj, i); 11 } 12 } 13}
3、for语句
1public class HelloWorld { 2 public void test() { 3 for (int i = 0; i < 10; i++) { 4 System.out.println(i); 5 } 6 } 7}
ASM编码实现
1import org.objectweb.asm.*; 2 3import static org.objectweb.asm.Opcodes.*; 4 5public class HelloWorldGenerateCore { 6 public static void main(String[] args) throws Exception { 7 String relative_path = "sample/HelloWorld.class"; 8 String filepath = FileUtils.getFilePath(relative_path); 9 10 // (1) 生成byte[]内容 11 byte[] bytes = dump(); 12 13 // (2) 保存byte[]到文件 14 FileUtils.writeBytes(filepath, bytes); 15 } 16 17 public static byte[] dump() throws Exception { 18 // (1) 创建ClassWriter对象 19 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); 20 21 // (2) 调用visitXxx()方法 22 cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, "sample/HelloWorld", 23 null, "java/lang/Object", null); 24 25 { 26 MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); 27 mv1.visitCode(); 28 mv1.visitVarInsn(ALOAD, 0); 29 mv1.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); 30 mv1.visitInsn(RETURN); 31 mv1.visitMaxs(0, 0); 32 mv1.visitEnd(); 33 } 34 35 { 36 MethodVisitor methodVisitor = cw.visitMethod(ACC_PUBLIC, "test", "()V", null, null); 37 Label conditionLabel = new Label(); 38 Label returnLabel = new Label(); 39 40 // 第1段 41 methodVisitor.visitCode(); 42 methodVisitor.visitInsn(ICONST_0); 43 methodVisitor.visitVarInsn(ISTORE, 1); 44 45 // 第2段 46 methodVisitor.visitLabel(conditionLabel); 47 methodVisitor.visitVarInsn(ILOAD, 1); 48 methodVisitor.visitIntInsn(BIPUSH, 10); 49 methodVisitor.visitJumpInsn(IF_ICMPGE, returnLabel); 50 methodVisitor.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 51 methodVisitor.visitVarInsn(ILOAD, 1); 52 methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(I)V", false); 53 methodVisitor.visitIincInsn(1, 1); 54 methodVisitor.visitJumpInsn(GOTO, conditionLabel); 55 56 // 第3段 57 methodVisitor.visitLabel(returnLabel); 58 methodVisitor.visitInsn(RETURN); 59 methodVisitor.visitMaxs(0, 0); 60 methodVisitor.visitEnd(); 61 } 62 63 cw.visitEnd(); 64 65 // (3) 调用toByteArray()方法 66 return cw.toByteArray(); 67 } 68}
验证结果
1public class HelloWorldRun { 2 public static void main(String[] args) throws Exception { 3 Class<?> clazz = Class.forName("sample.HelloWorld"); 4 Object obj = clazz.newInstance(); 5 6 Method method = clazz.getDeclaredMethod("test"); 7 method.invoke(obj); 8 } 9}
4、try-catch语句
1public class HelloWorld { 2 public void test() { 3 try { 4 System.out.println("Before Sleep"); 5 Thread.sleep(1000); 6 System.out.println("After Sleep"); 7 } catch (InterruptedException e) { 8 e.printStackTrace(); 9 } 10 } 11}
ASM编码实现
1public class HelloWorldGenerateCore { 2 public static void main(String[] args) throws Exception { 3 String relative_path = "sample/HelloWorld.class"; 4 String filepath = FileUtils.getFilePath(relative_path); 5 6 // (1) 生成byte[]内容 7 byte[] bytes = dump(); 8 9 // (2) 保存byte[]到文件 10 FileUtils.writeBytes(filepath, bytes); 11 } 12 13 public static byte[] dump() throws Exception { 14 // (1) 创建ClassWriter对象 15 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); 16 17 // (2) 调用visitXxx()方法 18 cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, "sample/HelloWorld", 19 null, "java/lang/Object", null); 20 21 { 22 MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); 23 mv1.visitCode(); 24 mv1.visitVarInsn(ALOAD, 0); 25 mv1.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); 26 mv1.visitInsn(RETURN); 27 mv1.visitMaxs(0, 0); 28 mv1.visitEnd(); 29 } 30 31 { 32 MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "test", "()V", null, null); 33 Label startLabel = new Label(); 34 Label endLabel = new Label(); 35 Label exceptionHandlerLabel = new Label(); 36 Label returnLabel = new Label(); 37 38 // 第1段 39 mv2.visitCode(); 40 // visitTryCatchBlock可以在这里访问 41 mv2.visitTryCatchBlock(startLabel, endLabel, exceptionHandlerLabel, "java/lang/InterruptedException"); 42 43 // 第2段 44 mv2.visitLabel(startLabel); 45 mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 46 mv2.visitLdcInsn("Before Sleep"); 47 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); 48 mv2.visitLdcInsn(new Long(1000L)); 49 mv2.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "sleep", "(J)V", false); 50 mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); 51 mv2.visitLdcInsn("After Sleep"); 52 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); 53 54 // 第3段 55 mv2.visitLabel(endLabel); 56 mv2.visitJumpInsn(GOTO, returnLabel); 57 58 // 第4段 59 mv2.visitLabel(exceptionHandlerLabel); 60 mv2.visitVarInsn(ASTORE, 1); 61 mv2.visitVarInsn(ALOAD, 1); 62 mv2.visitMethodInsn(INVOKEVIRTUAL, "java/lang/InterruptedException", "printStackTrace", "()V", false); 63 64 // 第5段 65 mv2.visitLabel(returnLabel); 66 mv2.visitInsn(RETURN); 67 68 // 第6段 69 // visitTryCatchBlock也可以在这里访问 70 // mv2.visitTryCatchBlock(startLabel, endLabel, exceptionHandlerLabel, "java/lang/InterruptedException"); 71 mv2.visitMaxs(0, 0); 72 mv2.visitEnd(); 73 } 74 75 cw.visitEnd(); 76 77 // (3) 调用toByteArray()方法 78 return cw.toByteArray(); 79 } 80}
验证结果
1public class HelloWorldRun { 2 public static void main(String[] args) throws Exception { 3 Class<?> clazz = Class.forName("sample.HelloWorld"); 4 Object obj = clazz.newInstance(); 5 6 Method method = clazz.getDeclaredMethod("test"); 7 method.invoke(obj); 8 } 9}
五、查看class文件的ASM代码
1.打印
当我们想对某一类进行ASM学习或者对想要实现的功能不知道如何实现时可以使用如下类进行ASM代码输出并查看
1public class ASMPrint { 2 public static void main(String[] args) throws IOException { 3 // (1) 设置参数 4 String className = "sample.HelloWorld"; 5 int parsingOptions = ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG; 6 boolean asmCode = true; 7 8 // (2) 打印结果 9 Printer printer = asmCode ? new ASMifier() : new Textifier(); 10 PrintWriter printWriter = new PrintWriter(System.out, true); 11 TraceClassVisitor traceClassVisitor = new TraceClassVisitor(null, printer, printWriter); 12 new ClassReader(className).accept(traceClassVisitor, parsingOptions); 13 } 14}
className值设置为类的全限定名,可以是我们自己写的类,例如sample.HelloWorld,也可以是JDK自带的类,例如java.lang.Comparable。
asmCode值设置为true或false。如果是true,可以打印出对应的ASM代码;如果是false,可以打印出方法对应的Instruction。
parsingOptions值设置为ClassReader.SKIP_CODE、ClassReader.SKIP_DEBUG、ClassReader.SKIP_FRAMES、ClassReader.EXPAND_FRAMES的组合值,也可以设置为0,可以打印出详细程度不同的信息。
2.插件
如果你是IDEA可以安装ASM ByteCode Viewer,然后选择要查看得java文件右键选择后可以在右侧看到ASPPlugin上看到对应得ByteCode、ASMified、Groovified。或者是插件ASM Bytecode Outline(本人用得社区版IDEA未达到效果)
六、TreeApi
Core API和Tree API的区别
- Tree API的优势:易用性:如果一个人在之前并没有接触过Core API和Tree API,那么Tree API更容易入手。功能性:在实现比较复杂的功能时,Tree API比Core API更容易实现。
- Core API的优势:执行效率:在实现相同功能的前提下,Core API要比Tree API执行效率高,花费时间少。内存使用:Core API比Tree API占用的内存空间少。
- 第一点,在ASM当中,不管是Core API,还是Tree API,都能够进行Class Generation、Class Transformation和Class Analysis操作。
- 第二点,Core API和Tree API是两者有各自的优势。Tree API易于使用、更容易实现复杂的操作;Core API执行速度更快、占用内存空间更少。
这里由于篇幅限制做了删减,如果有兴趣可以联系作者进行交流
七、文中用到的工具类
1、FileUtils
1public class FileUtils { 2 public static String getFilePath(String relativePath) { 3 String dir = FileUtils.class.getResource("/").getPath(); 4 return dir + relativePath; 5 } 6}
八、思考对于ASM我们以后能用于做些什么?
1、生成类----根据模版生成类(结合脚手架快速搭建项目以及项目初期模块快速搭建)
2、修改类----根据模版修改类(结合特定结构在java源代码编译生成.class字节码文件时对类进行修改以达到提升系统效率和释放开发人力的目的,可以结合IDEA插件开发开发类似于lombok或更为强大的插件)
作者:京东健康 马仁喜
来源:京东云开发者社区 转载请注明来源
