ASM字节码操作类库(打开java语言世界通往字节码世界的大门) ...

打印 上一主题 下一主题

主题 903|帖子 903|积分 2709

前言:授人以鱼不如授人以渔,应用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,MyBatis1星asm支持支持支持支持支持任意字节码插入,几乎不受限制学习难度大,编写代码多cglib5星javaassit支持支持支持支持支持java原始语法,字符串形式插入,写入直观不支持jdk1.5以上的语法,如泛型,增强forFastjson,MyBatis2星cglib支持支持支持支持支持与bytebuddy看起来差不多正在被bytebuddy淘汰EasyMock,jackson-databind3星bytebuddy支持支持支持支持支持支持任意维度的拦截,可以获取原始类、方法,以及代理类和全部参数不太直观,学习理解有些成本,API非常多SkyWalking,Mockito,Hibernate,powermock3星比较表格参考: http://xingyun.jd.com/shendeng/article/detail/7826
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文件
  1. public 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.     void function();
  19.     default String defaultFunction(Integer integer) {
  20.         System.out.println("param = " + integer);
  21.         return String.valueOf(integer);
  22.     }
  23.     static Integer getInteger(String str) {
  24.         return Integer.valueOf(str);
  25.     }
  26. }
复制代码
编码实现:
  1. public 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.         // (1) 生成byte[]内容
  6.         byte[] bytes = dump();
  7.         // (2) 保存byte[]到文件
  8.         FileUtils.writeBytes(filepath, bytes);
  9.     }
  10.     public static byte[] dump() throws Exception {
  11.         // (1) 创建ClassWriter对象
  12.         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
  13.         // (2) 调用visitXxx()方法,调用顺序和说明如下
  14.         /*
  15.          *  visit
  16.          *  [visitSource][visitModule][visitNestHost][visitPermittedSubclass][visitOuterClass]
  17.          *  (visitAnnotation |
  18.          *   visitTypeAnnotation |
  19.          *   visitAttribute)*
  20.          *  (visitNestMember |
  21.          *   visitInnerClass |
  22.          *   visitRecordComponent |
  23.          *   visitField |
  24.          *   visitMethod)*
  25.          *  visitEnd
  26.          *  []: 表示最多调用一次,可以不调用,但最多调用一次。
  27.          *  ()和|: 表示在多个方法之间,可以选择任意一个,并且多个方法之间不分前后顺序。
  28.          *  *: 表示方法可以调用0次或多次。
  29.          * */
  30.         //定义接口
  31.         /*
  32.          *visit(version, access, name, signature, superName, interfaces)
  33.          *version: 表示当前类的版本信息。在下述示例代码中,其取值为Opcodes.V1_8,表示使用Java 8版本。
  34.          *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部分。
  35.          *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的方式就是,将.字符转换成/字符。
  36.          *signature: 表示当前类的泛型信息。因为在这个接口当中不包含任何的泛型信息,因此它的值为null。
  37.          *superName: 表示当前类的父类信息,它采用的格式是Internal Name的形式。
  38.          *interfaces: 表示当前类实现了哪些接口信息。
  39.          **/
  40.         cw.visit(
  41.                 V1_8,                                        // version
  42.                 ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE,   // access
  43.                 "sample/ASMGenerateInterface",               // name
  44.                 null,                                        // signature
  45.                 "java/lang/Object",                          // superName
  46.                 null                                         // interfaces
  47.         );
  48.         //定义字段-基本类型
  49.         /*
  50.          * visitField(access, name, descriptor, signature, value)
  51.          *access参数:表示当前字段或方法带有的访问标识(access flag)信息,例如ACC_PUBLIC、ACC_STATIC和ACC_FINAL等。
  52.          *name参数:表示当前字段或方法的名字。
  53.          *descriptor参数:表示当前字段或方法的描述符。这些描述符,与我们平时使用的Java类型是有区别的。byte-B、short-S、int-I、char-C、具体可以参考如下示例代码
  54.          *signature参数:表示当前字段或方法是否带有泛型信息。换句话说,如果不带有泛型信息,提供一个null就可以了;如果带有泛型信息,就需要给它提供某一个具体的值。
  55.          *value参数:是visitField()方法的第5个参数。这个参数的取值,与当前字段是否为常量有关系。如果当前字段是一个常量,就需要给value参数提供某一个具体的值;如果当前字段不是常量,那么使用null就可以了。
  56.          * */
  57.         {
  58.             FieldVisitor fv1 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "byteType", "B", null, new Integer(1));
  59.             fv1.visitEnd();
  60.         }
  61.         {
  62.             FieldVisitor fv2 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "shortType", "S", null, new Integer(1));
  63.             fv2.visitEnd();
  64.         }
  65.         {
  66.             FieldVisitor fv3 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "intType", "I", null, new Integer(1));
  67.             fv3.visitEnd();
  68.         }
  69.         {
  70.             FieldVisitor fv4 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "charType", "C", null, 's');
  71.             fv4.visitEnd();
  72.         }
  73.         {
  74.             FieldVisitor fv5 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "floatType", "F", null, new Float("1.1"));
  75.             fv5.visitEnd();
  76.         }
  77.         {
  78.             FieldVisitor fv6 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "doubleType", "D", null, new Double("1.2"));
  79.             fv6.visitEnd();
  80.         }
  81.         {
  82.             FieldVisitor fv7 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "longType", "J", null, new Long(1L));
  83.             fv7.visitEnd();
  84.         }
  85.         {
  86.             FieldVisitor fv8 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "booleanType", "Z", null, new Integer(0));
  87.             fv8.visitEnd();
  88.         }
  89.         //定义变量-包装类型
  90.         {
  91.             FieldVisitor fv11 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "ByteType", "Ljava/lang/Byte;", null, null);
  92.             fv11.visitEnd();
  93.         }
  94.         {
  95.             FieldVisitor fv12 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "ShortType", "Ljava/lang/Short;", null,null);
  96.             fv12.visitEnd();
  97.         }
  98.         {
  99.             FieldVisitor fv13 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "IntegerType", "Ljava/lang/Integer;", null,null);
  100.             fv13.visitEnd();
  101.         }
  102.         {
  103.             FieldVisitor fv14 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "StringType", "Ljava/lang/String;", null, "s");
  104.             fv14.visitEnd();
  105.         }
  106.         {
  107.             FieldVisitor fv15 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "FloatType", "Ljava/lang/Float;", null,null);
  108.             fv15.visitEnd();
  109.         }
  110.         {
  111.             FieldVisitor fv16 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "DoubleType", "Ljava/lang/Double;", null,null);
  112.             fv16.visitEnd();
  113.         }
  114.         {
  115.             FieldVisitor fv17 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "LongType", "Ljava/lang/Long;", null,  null);
  116.             fv17.visitEnd();
  117.         }
  118.         {
  119.             FieldVisitor fv18 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "BooleanType", "Ljava/lang/Boolean;", null, null);
  120.             fv18.visitEnd();
  121.         }
  122.         //定义方法-抽象方法
  123.         /*
  124.          * visitMethod(access, name, descriptor, signature, exceptions)
  125.          *access参数:表示当前字段或方法带有的访问标识(access flag)信息,例如ACC_PUBLIC、ACC_STATIC和ACC_FINAL等。
  126.          *name参数:表示当前字段或方法的名字。
  127.          *descriptor参数:表示当前字段或方法的描述符。这些描述符,与我们平时使用的Java类型是有区别的。()内为入参,后面为反参
  128.          *signature参数:表示当前字段或方法是否带有泛型信息。换句话说,如果不带有泛型信息,提供一个null就可以了;如果带有泛型信息,就需要给它提供某一个具体的值。
  129.          *exceptions参数:是visitMethod()方法的第5个参数。这个参数的取值,与当前方法声明中是否具有throws XxxException相关。
  130.          * */
  131.         {
  132.             MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "function", "()V", null, null);
  133.             mv1.visitEnd();
  134.         }
  135.         //定义方法-默认方法
  136.         {
  137.             MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "defaultFunction", "(Ljava/lang/Integer;)Ljava/lang/String;", null, null);
  138.             mv2.visitCode();
  139.             mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
  140.             mv2.visitTypeInsn(NEW, "java/lang/StringBuilder");
  141.             mv2.visitInsn(DUP);
  142.             mv2.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false);
  143.             mv2.visitLdcInsn("param = ");
  144.             mv2.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
  145.             mv2.visitVarInsn(ALOAD, 1);
  146.             mv2.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", false);
  147.             mv2.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
  148.             mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
  149.             mv2.visitVarInsn(ALOAD, 1);
  150.             mv2.visitMethodInsn(INVOKESTATIC, "java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;", false);
  151.             mv2.visitInsn(ARETURN);
  152.             mv2.visitMaxs(3, 2);
  153.             mv2.visitEnd();
  154.         }
  155.         //定义方法-静态方法
  156.         {
  157.             MethodVisitor mv3 = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "getInteger", "(Ljava/lang/String;)Ljava/lang/Integer;", null, null);
  158.             mv3.visitCode();
  159.             mv3.visitVarInsn(ALOAD, 0);
  160.             mv3.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(Ljava/lang/String;)Ljava/lang/Integer;", false);
  161.             mv3.visitInsn(ARETURN);
  162.             mv3.visitMaxs(1, 1);
  163.             mv3.visitEnd();
  164.         }
  165.         {
  166.             MethodVisitor mv4 = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
  167.             mv4.visitCode();
  168.             mv4.visitInsn(ICONST_1);
  169.             mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false);
  170.             mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "ByteType", "Ljava/lang/Byte;");
  171.             mv4.visitInsn(ICONST_1);
  172.             mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false);
  173.             mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "ShortType", "Ljava/lang/Short;");
  174.             mv4.visitInsn(ICONST_1);
  175.             mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false);
  176.             mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "IntegerType", "Ljava/lang/Integer;");
  177.             mv4.visitLdcInsn(new Float("1.1"));
  178.             mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false);
  179.             mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "FloatType", "Ljava/lang/Float;");
  180.             mv4.visitLdcInsn(new Double("1.1"));
  181.             mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false);
  182.             mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "DoubleType", "Ljava/lang/Double;");
  183.             mv4.visitInsn(LCONST_1);
  184.             mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false);
  185.             mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "LongType", "Ljava/lang/Long;");
  186.             mv4.visitInsn(ICONST_1);
  187.             mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
  188.             mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "BooleanType", "Ljava/lang/Boolean;");
  189.             mv4.visitInsn(RETURN);
  190.             mv4.visitMaxs(2, 0);
  191.             mv4.visitEnd();
  192.         }
  193.         cw.visitEnd(); // 注意,最后要调用visitEnd()方法
  194.         // (3) 调用toByteArray()方法
  195.         return cw.toByteArray();
  196.     }
  197. }
复制代码
验证结果:

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

1、修改类的版本

ClassVisitor子类实现
  1. public class ClassChangeVersionVisitor extends ClassVisitor {
  2.     public ClassChangeVersionVisitor(int api, ClassVisitor classVisitor) {
  3.         super(api, classVisitor);
  4.     }
  5.     @Override
  6.     public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
  7.         super.visit(Opcodes.V1_7, access, name, signature, superName, interfaces);
  8.     }
  9. }
复制代码
使用ClassVisitor的子类ClassChangeVersionVisitor进行类的版本修改
  1. public 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.         //(1)构建ClassReader
  7.         ClassReader cr = new ClassReader(bytes);
  8.         //(2)构建ClassWriter
  9.         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
  10.         //(3)串连ClassVisitor
  11.         int api = Opcodes.ASM9;
  12.         ClassVisitor cv = new ClassChangeVersionVisitor(api, cw);
  13.         //(4)结合ClassReader和ClassVisitor
  14.         int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
  15.         cr.accept(cv, parsingOptions);
  16.         //(5)生成byte[]
  17.         byte[] bytes2 = cw.toByteArray();
  18.         FileUtils.writeBytes(filepath, bytes2);
  19.     }
  20. }
复制代码
验证&效果

通过javap -p -v HelloWorld命令可以看到版本号信息已从52调整位51

2.给每个方法添加计算调用时间

对目标类进行方法改造调换---为每个方法添加用时计算
  1. public class HelloWorld {
  2.     public int add(int a, int b) throws InterruptedException {
  3.         int c = a + b;
  4.         Random rand = new Random(System.currentTimeMillis());
  5.         int num = rand.nextInt(300);
  6.         Thread.sleep(100 + num);
  7.         return c;
  8.     }
  9.     public int sub(int a, int b) throws InterruptedException {
  10.         int c = a - b;
  11.         Random rand = new Random(System.currentTimeMillis());
  12.         int num = rand.nextInt(400);
  13.         Thread.sleep(100 + num);
  14.         return c;
  15.     }
  16. }
复制代码
ASM编码实现
  1. public class MethodTimerVisitor2 extends ClassVisitor {
  2.     private String owner;
  3.     private boolean isInterface;
  4.     public MethodTimerVisitor2(int api, ClassVisitor classVisitor) {
  5.         super(api, classVisitor);
  6.     }
  7.     @Override
  8.     public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
  9.         super.visit(version, access, name, signature, superName, interfaces);
  10.         owner = name;
  11.         isInterface = (access & ACC_INTERFACE) != 0;
  12.     }
  13.     @Override
  14.     public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
  15.         MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
  16.         if (!isInterface && mv != null && !"<init>".equals(name) && !"<clinit>".equals(name)) {
  17.             boolean isAbstractMethod = (access & ACC_ABSTRACT) != 0;
  18.             boolean isNativeMethod = (access & ACC_NATIVE) != 0;
  19.             if (!isAbstractMethod && !isNativeMethod) {
  20.                 // 每遇到一个合适的方法,就添加一个相应的字段
  21.                 FieldVisitor fv = super.visitField(ACC_PUBLIC | ACC_STATIC, getFieldName(name), "J", null, null);
  22.                 if (fv != null) {
  23.                     fv.visitEnd();
  24.                 }
  25.                 mv = new MethodTimerAdapter2(api, mv, owner, name);
  26.             }
  27.         }
  28.         return mv;
  29.     }
  30.     private String getFieldName(String methodName) {
  31.         return "timer_" + methodName;
  32.     }
  33.     private class MethodTimerAdapter2 extends MethodVisitor {
  34.         private final String owner;
  35.         private final String methodName;
  36.         public MethodTimerAdapter2(int api, MethodVisitor mv, String owner, String methodName) {
  37.             super(api, mv);
  38.             this.owner = owner;
  39.             this.methodName = methodName;
  40.         }
  41.         @Override
  42.         public void visitCode() {
  43.             // 首先,处理自己的代码逻辑
  44.             super.visitFieldInsn(GETSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应
  45.             super.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false);
  46.             super.visitInsn(LSUB);
  47.             super.visitFieldInsn(PUTSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应
  48.             // 其次,调用父类的方法实现
  49.             super.visitCode();
  50.         }
  51.         @Override
  52.         public void visitInsn(int opcode) {
  53.             // 首先,处理自己的代码逻辑
  54.             if ((opcode >= IRETURN && opcode <= RETURN) || opcode == ATHROW) {
  55.                 super.visitFieldInsn(GETSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应
  56.                 super.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false);
  57.                 super.visitInsn(LADD);
  58.                 super.visitFieldInsn(PUTSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应
  59.             }
  60.             // 其次,调用父类的方法实现
  61.             super.visitInsn(opcode);
  62.         }
  63.     }
  64. }
复制代码
2、switch语句
  1. public class HelloWorldTransformCore {
  2.     private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
  3.   
  4.     public static void main(String[] args) {
  5.         String relative_path = "sample/HelloWorld.class";
  6.         String dir = HelloWorldTransformCore.class.getResource("/").getPath();
  7.         String filepath = dir + relative_path;
  8.         File file = new File(filepath);
  9.         try {
  10.             InputStream in = new FileInputStream(file);
  11.             in = new BufferedInputStream(in);
  12.             ByteArrayOutputStream bao = new ByteArrayOutputStream();
  13.             copyLarge(in, bao, new byte[DEFAULT_BUFFER_SIZE]);
  14.             byte[] bytes1 = bao.toByteArray();
  15.             //(1)构建ClassReader
  16.             ClassReader cr = new ClassReader(bytes1);
  17.             //(2)构建ClassWriter
  18.             ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
  19.             //(3)串连ClassVisitor
  20.             int api = Opcodes.ASM9;
  21.             ClassVisitor cv = new MethodTimerVisitor2(api, cw);
  22.             //(4)结合ClassReader和ClassVisitor
  23.             int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
  24.             cr.accept(cv, parsingOptions);
  25.             //(5)生成byte[]
  26.             byte[] bytes2 = cw.toByteArray();
  27.             OutputStream out = new FileOutputStream(filepath);
  28.             BufferedOutputStream buff = new BufferedOutputStream(out);
  29.             buff.write(bytes2);
  30.             buff.flush();
  31.             buff.close();
  32.             System.out.println("file://" + filepath);
  33.         } catch (IOException e) {
  34.             e.printStackTrace();
  35.         }
  36.     }
  37.     public static long copyLarge(final InputStream input, final OutputStream output, final byte[] buffer)
  38.             throws IOException {
  39.         long count = 0;
  40.         int n;
  41.         while (-1 != (n = input.read(buffer))) {
  42.             output.write(buffer, 0, n);
  43.             count += n;
  44.         }
  45.         return count;
  46.     }
  47. }
复制代码
ASM编码实现
  1. public 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.         Class<?> clazz = HelloWorld.class;
  23.         Field[] declaredFields = clazz.getDeclaredFields();
  24.         for (Field f : declaredFields) {
  25.             String fieldName = f.getName();
  26.             f.setAccessible(true);
  27.             if (fieldName.startsWith("timer")) {
  28.                 Object FieldValue = f.get(null);
  29.                 System.out.println(fieldName + " = " + FieldValue);
  30.             }
  31.         }
  32.     }
  33. }
复制代码
验证结果
  1. public 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. }
复制代码
3、for语句
  1. public 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.         System.out.println(hashCode);
  9.         return hashCode;
  10.     }
  11. }
复制代码
ASM编码实现
  1. public class ParameterUtils {
  2.     private static final DateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  3.     public static void printValueOnStack(boolean value) {
  4.         System.out.println("    " + value);
  5.     }
  6.     public static void printValueOnStack(byte value) {
  7.         System.out.println("    " + value);
  8.     }
  9.     public static void printValueOnStack(char value) {
  10.         System.out.println("    " + value);
  11.     }
  12.     public static void printValueOnStack(short value) {
  13.         System.out.println("    " + value);
  14.     }
  15.     public static void printValueOnStack(int value) {
  16.         System.out.println("    " + value);
  17.     }
  18.     public static void printValueOnStack(float value) {
  19.         System.out.println("    " + value);
  20.     }
  21.     public static void printValueOnStack(long value) {
  22.         System.out.println("    " + value);
  23.     }
  24.     public static void printValueOnStack(double value) {
  25.         System.out.println("    " + value);
  26.     }
  27.     public static void printValueOnStack(Object value) {
  28.         if (value == null) {
  29.             System.out.println("    " + value);
  30.         }
  31.         else if (value instanceof String) {
  32.             System.out.println("    " + value);
  33.         }
  34.         else if (value instanceof Date) {
  35.             System.out.println("    " + fm.format(value));
  36.         }
  37.         else if (value instanceof char[]) {
  38.             System.out.println("    " + Arrays.toString((char[])value));
  39.         }
  40.         else {
  41.             System.out.println("    " + value.getClass() + ": " + value.toString());
  42.         }
  43.     }
  44.     public static void printText(String str) {
  45.         System.out.println(str);
  46.     }
  47. }
复制代码
验证结果
  1. public class MethodParameterVisitor2 extends ClassVisitor {
  2.     public MethodParameterVisitor2(int api, ClassVisitor classVisitor) {
  3.         super(api, classVisitor);
  4.     }
  5.     @Override
  6.     public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
  7.         MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
  8.         if (mv != null && !name.equals("<init>")) {
  9.             boolean isAbstractMethod = (access & ACC_ABSTRACT) != 0;
  10.             boolean isNativeMethod = (access & ACC_NATIVE) != 0;
  11.             if (!isAbstractMethod && !isNativeMethod) {
  12.                 mv = new MethodParameterAdapter2(api, mv, access, name, descriptor);
  13.             }
  14.         }
  15.         return mv;
  16.     }
  17.     private static class MethodParameterAdapter2 extends MethodVisitor {
  18.         private final int methodAccess;
  19.         private final String methodName;
  20.         private final String methodDesc;
  21.         public MethodParameterAdapter2(int api, MethodVisitor mv, int methodAccess, String methodName, String methodDesc) {
  22.             super(api, mv);
  23.             this.methodAccess = methodAccess;
  24.             this.methodName = methodName;
  25.             this.methodDesc = methodDesc;
  26.         }
  27.         @Override
  28.         public void visitCode() {
  29.             // 首先,处理自己的代码逻辑
  30.             boolean isStatic = ((methodAccess & ACC_STATIC) != 0);
  31.             int slotIndex = isStatic ? 0 : 1;
  32.             printMessage("Method Enter: " + methodName + methodDesc);
  33.             Type methodType = Type.getMethodType(methodDesc);
  34.             Type[] argumentTypes = methodType.getArgumentTypes();
  35.             for (Type t : argumentTypes) {
  36.                 int sort = t.getSort();
  37.                 int size = t.getSize();
  38.                 String descriptor = t.getDescriptor();
  39.                 int opcode = t.getOpcode(ILOAD);
  40.                 super.visitVarInsn(opcode, slotIndex);
  41.                 if (sort >= Type.BOOLEAN && sort <= Type.DOUBLE) {
  42.                     String methodDesc = String.format("(%s)V", descriptor);
  43.                     printValueOnStack(methodDesc);
  44.                 }
  45.                 else {
  46.                     printValueOnStack("(Ljava/lang/Object;)V");
  47.                 }
  48.                 slotIndex += size;
  49.             }
  50.             // 其次,调用父类的方法实现
  51.             super.visitCode();
  52.         }
  53.         @Override
  54.         public void visitInsn(int opcode) {
  55.             // 首先,处理自己的代码逻辑
  56.             if ((opcode >= IRETURN && opcode <= RETURN) || opcode == ATHROW) {
  57.                 printMessage("Method Exit: " + methodName + methodDesc);
  58.                 if (opcode >= IRETURN && opcode <= DRETURN) {
  59.                     Type methodType = Type.getMethodType(methodDesc);
  60.                     Type returnType = methodType.getReturnType();
  61.                     int size = returnType.getSize();
  62.                     String descriptor = returnType.getDescriptor();
  63.                     if (size == 1) {
  64.                         super.visitInsn(DUP);
  65.                     }
  66.                     else {
  67.                         super.visitInsn(DUP2);
  68.                     }
  69.                     String methodDesc = String.format("(%s)V", descriptor);
  70.                     printValueOnStack(methodDesc);
  71.                 }
  72.                 else if (opcode == ARETURN) {
  73.                     super.visitInsn(DUP);
  74.                     printValueOnStack("(Ljava/lang/Object;)V");
  75.                 }
  76.                 else if (opcode == RETURN) {
  77.                     printMessage("    return void");
  78.                 }
  79.                 else {
  80.                     printMessage("    abnormal return");
  81.                 }
  82.             }
  83.             // 其次,调用父类的方法实现
  84.             super.visitInsn(opcode);
  85.         }
  86.         private void printMessage(String str) {
  87.             super.visitLdcInsn(str);
  88.             super.visitMethodInsn(INVOKESTATIC, "sample/ParameterUtils", "printText", "(Ljava/lang/String;)V", false);
  89.         }
  90.         private void printValueOnStack(String descriptor) {
  91.             super.visitMethodInsn(INVOKESTATIC, "sample/ParameterUtils", "printValueOnStack", descriptor, false);
  92.         }
  93.     }
  94. }
复制代码
4、try-catch语句
  1. public class HelloWorldTransformCore {
  2.     public static void main(String[] args) {
  3.         String relative_path = "sample/HelloWorld.class";
  4.         String filepath = FileUtils.getFilePath(relative_path);
  5.         byte[] bytes1 = FileUtils.readBytes(filepath);
  6.         //(1)构建ClassReader
  7.         ClassReader cr = new ClassReader(bytes1);
  8.         //(2)构建ClassWriter
  9.         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
  10.         //(3)串连ClassVisitor
  11.         int api = Opcodes.ASM9;
  12.         ClassVisitor cv = new MethodParameterVisitor2(api, cw);
  13.         //(4)结合ClassReader和ClassVisitor
  14.         int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
  15.         cr.accept(cv, parsingOptions);
  16.         //(5)生成byte[]
  17.         byte[] bytes2 = cw.toByteArray();
  18.         FileUtils.writeBytes(filepath, bytes2);
  19.     }
  20. }
复制代码
ASM编码实现
  1. public 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.         if (remainder == 0) {
  7.             System.out.println("hashCode is even number.");
  8.         }
  9.         else {
  10.             System.out.println("hashCode is odd number.");
  11.         }
  12.     }
  13. }
复制代码
验证结果
  1. public class MethodParameterVisitor2 extends ClassVisitor {
  2.     public MethodParameterVisitor2(int api, ClassVisitor classVisitor) {
  3.         super(api, classVisitor);
  4.     }
  5.     @Override
  6.     public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
  7.         MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
  8.         if (mv != null && !name.equals("<init>")) {
  9.             boolean isAbstractMethod = (access & ACC_ABSTRACT) != 0;
  10.             boolean isNativeMethod = (access & ACC_NATIVE) != 0;
  11.             if (!isAbstractMethod && !isNativeMethod) {
  12.                 mv = new MethodParameterAdapter2(api, mv, access, name, descriptor);
  13.             }
  14.         }
  15.         return mv;
  16.     }
  17.     private static class MethodParameterAdapter2 extends MethodVisitor {
  18.         private final int methodAccess;
  19.         private final String methodName;
  20.         private final String methodDesc;
  21.         public MethodParameterAdapter2(int api, MethodVisitor mv, int methodAccess, String methodName, String methodDesc) {
  22.             super(api, mv);
  23.             this.methodAccess = methodAccess;
  24.             this.methodName = methodName;
  25.             this.methodDesc = methodDesc;
  26.         }
  27.         @Override
  28.         public void visitCode() {
  29.             // 首先,处理自己的代码逻辑
  30.             boolean isStatic = ((methodAccess & ACC_STATIC) != 0);
  31.             int slotIndex = isStatic ? 0 : 1;
  32.             printMessage("Method Enter: " + methodName + methodDesc);
  33.             Type methodType = Type.getMethodType(methodDesc);
  34.             Type[] argumentTypes = methodType.getArgumentTypes();
  35.             for (Type t : argumentTypes) {
  36.                 int sort = t.getSort();
  37.                 int size = t.getSize();
  38.                 String descriptor = t.getDescriptor();
  39.                 int opcode = t.getOpcode(ILOAD);
  40.                 super.visitVarInsn(opcode, slotIndex);
  41.                 if (sort >= Type.BOOLEAN && sort <= Type.DOUBLE) {
  42.                     String methodDesc = String.format("(%s)V", descriptor);
  43.                     printValueOnStack(methodDesc);
  44.                 }
  45.                 else {
  46.                     printValueOnStack("(Ljava/lang/Object;)V");
  47.                 }
  48.                 slotIndex += size;
  49.             }
  50.             // 其次,调用父类的方法实现
  51.             super.visitCode();
  52.         }
  53.         @Override
  54.         public void visitInsn(int opcode) {
  55.             // 首先,处理自己的代码逻辑
  56.             if ((opcode >= IRETURN && opcode <= RETURN) || opcode == ATHROW) {
  57.                 printMessage("Method Exit: " + methodName + methodDesc);
  58.                 if (opcode >= IRETURN && opcode <= DRETURN) {
  59.                     Type methodType = Type.getMethodType(methodDesc);
  60.                     Type returnType = methodType.getReturnType();
  61.                     int size = returnType.getSize();
  62.                     String descriptor = returnType.getDescriptor();
  63.                     if (size == 1) {
  64.                         super.visitInsn(DUP);
  65.                     }
  66.                     else {
  67.                         super.visitInsn(DUP2);
  68.                     }
  69.                     String methodDesc = String.format("(%s)V", descriptor);
  70.                     printValueOnStack(methodDesc);
  71.                 }
  72.                 else if (opcode == ARETURN) {
  73.                     super.visitInsn(DUP);
  74.                     printValueOnStack("(Ljava/lang/Object;)V");
  75.                 }
  76.                 else if (opcode == RETURN) {
  77.                     printMessage("    return void");
  78.                 }
  79.                 else {
  80.                     printMessage("    abnormal return");
  81.                 }
  82.             }
  83.             // 其次,调用父类的方法实现
  84.             super.visitInsn(opcode);
  85.         }
  86.         private void printMessage(String str) {
  87.             super.visitLdcInsn(str);
  88.             super.visitMethodInsn(INVOKESTATIC, "sample/ParameterUtils", "printText", "(Ljava/lang/String;)V", false);
  89.         }
  90.         private void printValueOnStack(String descriptor) {
  91.             super.visitMethodInsn(INVOKESTATIC, "sample/ParameterUtils", "printValueOnStack", descriptor, false);
  92.         }
  93.     }
  94. }
复制代码
五、查看class文件的ASM代码

1.打印

当我们想对某一类进行ASM学习或者对想要实现的功能不知道如何实现时可以使用如下类进行ASM代码输出并查看
  1. public 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.         // (1) 生成byte[]内容
  6.         byte[] bytes = dump();
  7.         // (2) 保存byte[]到文件
  8.         FileUtils.writeBytes(filepath, bytes);
  9.     }
  10.     public static byte[] dump() throws Exception {
  11.         // (1) 创建ClassWriter对象
  12.         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
  13.         // (2) 调用visitXxx()方法
  14.         cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, "sample/HelloWorld",
  15.                 null, "java/lang/Object", null);
  16.         {
  17.             MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
  18.             mv1.visitCode();
  19.             mv1.visitVarInsn(ALOAD, 0);
  20.             mv1.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
  21.             mv1.visitInsn(RETURN);
  22.             mv1.visitMaxs(0, 0);
  23.             mv1.visitEnd();
  24.         }
  25.         {
  26.             MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "test", "(I)V", null, null);
  27.             Label elseLabel = new Label();
  28.             Label returnLabel = new Label();
  29.             // 第1段
  30.             mv2.visitCode();
  31.             mv2.visitVarInsn(ILOAD, 1);
  32.             mv2.visitJumpInsn(IFNE, elseLabel);
  33.             mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
  34.             mv2.visitLdcInsn("value is 0");
  35.             mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
  36.             mv2.visitJumpInsn(GOTO, returnLabel);
  37.             // 第2段
  38.             mv2.visitLabel(elseLabel);
  39.             mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
  40.             mv2.visitLdcInsn("value is not 0");
  41.             mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
  42.             // 第3段
  43.             mv2.visitLabel(returnLabel);
  44.             mv2.visitInsn(RETURN);
  45.             mv2.visitMaxs(0, 0);
  46.             mv2.visitEnd();
  47.         }
  48.         cw.visitEnd();
  49.         // (3) 调用toByteArray()方法
  50.         return cw.toByteArray();
  51.     }
  52. }
复制代码
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
  1. public class HelloWorldRun {
  2.     public static void main(String[] args) throws Exception {
  3.         Class<?> clazz = Class.forName("sample.HelloWorld");
  4.         Object obj = clazz.newInstance();
  5.         Method method = clazz.getDeclaredMethod("test", int.class);
  6.         method.invoke(obj, 0);
  7.         method.invoke(obj, 1);
  8.     }
  9. }
复制代码
八、思考对于ASM我们以后能用于做些什么?

1、生成类----根据模版生成类(结合脚手架快速搭建项目以及项目初期模块快速搭建)
2、修改类----根据模版修改类(结合特定结构在java源代码编译生成.class字节码文件时对类进行修改以达到提升系统效率和释放开发人力的目的,可以结合IDEA插件开发开发类似于lombok或更为强大的插件)
作者:京东健康 马仁喜
来源:京东云开发者社区 转载请注明来源

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

知者何南

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表