Use ASM to operate Java bytecode to implement AOP principles
This article uses an example to generate a Java bytecode file dynamically Using ASM (. class) or after loading the bytecode, dynamically modify the bytecode and add the code we need to execute to simulate the implementation of Spring AOP.
At the end of the year, I am not in the mood to write the text. I will paste the several types of code in the demo. After the code is copied, it can be directly used without any other errors.
Use asm-5.0.3.jar
The package of the demo project is com. shanhy. demo. asm. hello.
Five Java files:
AopClassAdapter. java
In the AopInteceptor. java method to be modified, we are going to add our own code Logic
AopMethodVisitor. java modify bytecode
HelloGeneratorClass. java dynamically generates java classes through asm. The main method for testing is also here
MyClassLoader. java custom ClassLoader
Package com. shanhy. demo. asm. hello; import org. objectweb. asm. classVisitor; import org. objectweb. asm. methodVisitor; import org. objectweb. asm. opcodes; public class AopClassAdapter extends ClassVisitor implements Opcodes {public AopClassAdapter (int api, ClassVisitor cv) {super (api, cv);} @ Override public MethodVisitor visitMethod (int access, String name, string desc, String signature, String [] exceptions) {MethodVisitor mv = super. visitMethod (access, name, desc, signature, exceptions); // special processing of Methods Starting with test if (name. startsWith ("test") {mv = new AopMethodVisitor (this. api, mv) ;}return mv ;}}
package com.shanhy.demo.asm.hello;public class AopInteceptor { public static void before(){ System.out.println(".......before()......."); } public static void after(){ System.out.println(".......after()......."); }}
Package com. shanhy. demo. asm. hello; import org. objectweb. asm. methodVisitor; import org. objectweb. asm. opcodes; public class AopMethodVisitor extends MethodVisitor implements Opcodes {public AopMethodVisitor (int api, MethodVisitor mv) {super (api, mv) ;}@ Override public void visitCode () {super. visitCode (); this. visitMethodInsn (INVOKESTATIC, "com/shanhy/demo/asm/hello/AopInteceptor", "before", "() V", f Alse) ;}@ Override public void visitInsn (int opcode) {if (opcode> = IRETURN & opcode <= RETURN) // Insert the after code before returning. This. visitMethodInsn (INVOKESTATIC, "com/shanhy/demo/asm/hello/AopInteceptor", "after", "() V", false); super. visitInsn (opcode );}}
Package com. shanhy. demo. asm. hello; import java. io. file; import java. io. fileOutputStream; import java. lang. reflect. method; import org. objectweb. asm. classReader; import org. objectweb. asm. classWriter; import org. objectweb. asm. fieldVisitor; import org. objectweb. asm. label; import org. objectweb. asm. methodVisitor; import org. objectweb. asm. opcodes;/*** use ASM to generate the class bytecode ** @ author Administrator **/public class HelloG EneratorClass implements Opcodes {/*** use to construct Hello class bytecode * Hello. java in package is only a code prototype. In this example, it is only for comparison and is not actually used. * The ASM code generation tool uses bytecode ** @ return * @ throws Exception * @ author SHANHY * @ create February 3, 2016 */public static byte [] generatorHelloClass () throws Exception {ClassWriter cw = new ClassWriter (0); FieldVisitor fv; MethodVisitor mv; cw. visit (V1_7, ACC_PUBLIC + ACC_SUPER, "com/shanhy/demo/asm/hello/Hello", null, "java/lang/Object", null); cw. visitSource ("Hello. java ", null); {fv = cw. visitField (ACC_PUBLIC + ACC_FINAL + ACC_STATIC, "FLAG", "Ljava/lang/String;", null, "\ u6211 \ u662f \ u5e38 \ u91cf"); fv. visitEnd () ;}{ mv = cw. visitMethod (ACC_PUBLIC ,"
"," () V ", null, null); mv. visitCode (); Label l0 = new Label (); mv. visitLabel (l0); mv. visitVarInsn (ALOAD, 0); mv. visitMethodInsn (INVOKESPECIAL, "java/lang/Object ","
"," () V ", false); mv. visitInsn (RETURN); Label l1 = new Label (); mv. visitLabel (l1); mv. visitMaxs (1, 1); mv. visitEnd () ;}{ mv = cw. visitMethod (ACC_PUBLIC, "display", "() V", null, null); mv. visitCode (); Label l0 = new Label (); mv. visitLabel (l0); mv. visitInsn (ICONST_0); mv. visitVarInsn (ISTORE, 1); Label l1 = new Label (); mv. visitLabel (l1); Label l2 = new Label (); mv. visitJumpInsn (GOTO, l2); Label l3 = new Label (); mv. visitLabel (l3); mv. visitFrame (Opcodes. f_APPEND, 1, new Object [] {Opcodes. INTEGER}, 0, null); mv. visitFieldInsn (GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv. visitLdcInsn (">>>>>>>>>>\ u6211 \ u662f \ u5e38 \ u91cf"); mv. visitMethodInsn (INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;) V", false); Label l4 = new Label (); mv. visitLabel (l4); mv. visitIincInsn (1, 1); mv. visitLabel (l2); mv. visitFrame (Opcodes. f_SAME, 0, null, 0, null); mv. visitVarInsn (ILOAD, 1); mv. visitIntInsn (BIPUSH, 8); mv. visitJumpInsn (IF_ICMPLT, l3); Label l5 = new Label (); mv. visitLabel (l5); mv. visitInsn (RETURN); Label l6 = new Label (); mv. visitLabel (l6); mv. visitMaxs (2, 2); mv. visitEnd () ;}{ mv = cw. visitMethod (ACC_PUBLIC, "testList", "() Ljava/util/List;", "() Ljava/util/List
; ", Null); mv. visitCode (); Label l0 = new Label (); mv. visitLabel (l0); mv. visitTypeInsn (NEW, "java/util/ArrayList"); mv. visitInsn (DUP); mv. visitMethodInsn (INVOKESPECIAL, "java/util/ArrayList ","
"," () V ", false); mv. visitVarInsn (ASTORE, 1); Label l1 = new Label (); mv. visitLabel (l1); mv. visitVarInsn (ALOAD, 1); mv. visitLdcInsn ("Tome"); mv. visitMethodInsn (INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;) Z", true); mv. visitInsn (POP); Label l2 = new Label (); mv. visitLabel (l2); mv. visitVarInsn (ALOAD, 1); mv. visitLdcInsn ("Jack"); mv. visitMethodInsn (INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;) Z", true); mv. visitInsn (POP); Label l3 = new Label (); mv. visitLabel (l3); mv. visitVarInsn (ALOAD, 1); mv. visitLdcInsn ("Lily"); mv. visitMethodInsn (INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;) Z", true); mv. visitInsn (POP); Label l4 = new Label (); mv. visitLabel (l4); mv. visitFieldInsn (GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv. visitTypeInsn (NEW, "java/lang/StringBuilder"); mv. visitInsn (DUP); mv. visitLdcInsn (">>>>>>>>> testList> list. size = "); mv. visitMethodInsn (INVOKESPECIAL, "java/lang/StringBuilder ","
"," (Ljava/lang/String;) V ", false); mv. visitVarInsn (ALOAD, 1); mv. visitMethodInsn (INVOKEINTERFACE, "java/util/List", "size", "() I", true); mv. visitMethodInsn (INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(I) Ljava/lang/StringBuilder;", false); mv. visitMethodInsn (INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "() Ljava/lang/String;", false); mv. visitMethodInsn (INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;) V", false); Label l5 = new Label (); mv. visitLabel (l5); mv. visitVarInsn (ALOAD, 1); mv. visitInsn (ARETURN); Label l6 = new Label (); mv. visitLabel (l6); mv. visitMaxs (4, 2); mv. visitEnd () ;}{ mv = cw. visitMethod (ACC_PUBLIC + ACC_VARARGS, "testMapList", "(Z [Ljava/util/Map;) Ljava/util/List;", "(Z [Ljava/util/Map
;) Ljava/util/List
;>; ", Null); mv. visitCode (); Label l0 = new Label (); mv. visitLabel (l0); mv. visitTypeInsn (NEW, "java/util/ArrayList"); mv. visitInsn (DUP); mv. visitMethodInsn (INVOKESPECIAL, "java/util/ArrayList ","
"," () V ", false); mv. visitVarInsn (ASTORE, 3); Label l1 = new Label (); mv. visitLabel (l1); mv. visitVarInsn (ILOAD, 1); Label l2 = new Label (); mv. visitJumpInsn (IFEQ, l2); Label l3 = new Label (); mv. visitLabel (l3); mv. visitVarInsn (ALOAD, 2); mv. visitInsn (DUP); mv. visitVarInsn (ASTORE, 7); mv. visitInsn (ARRAYLENGTH); mv. visitVarInsn (ISTORE, 6); mv. visitInsn (ICONST_0); mv. visitVarInsn (ISTORE, 5); Label l4 = new Label (); mv. visitJumpInsn (GOTO, l4); Label l5 = new Label (); mv. visitLabel (l5); mv. visitFrame (Opcodes. f_FULL, 8, new Object [] {"com/shanhy/demo/asm/hello/Hello", Opcodes. INTEGER, "[Ljava/util/Map;", "java/util/List", Opcodes. TOP, Opcodes. INTEGER, Opcodes. INTEGER, "[Ljava/util/Map;"}, 0, new Object [] {}); mv. visitVarInsn (ALOAD, 7); mv. visitVarInsn (ILOAD, 5); mv. visitInsn (AALOAD); mv. visitVarInsn (ASTORE, 4); Label l6 = new Label (); mv. visitLabel (l6); mv. visitVarInsn (ALOAD, 3); mv. visitVarInsn (ALOAD, 4); mv. visitMethodInsn (INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;) Z", true); mv. visitInsn (POP); Label l7 = new Label (); mv. visitLabel (l7); mv. visitIincInsn (5, 1); mv. visitLabel (l4); mv. visitFrame (Opcodes. f_SAME, 0, null, 0, null); mv. visitVarInsn (ILOAD, 5); mv. visitVarInsn (ILOAD, 6); mv. visitJumpInsn (IF_ICMPLT, l5); mv. visitLabel (l2); mv. visitFrame (Opcodes. f_FULL, 4, new Object [] {"com/shanhy/demo/asm/hello/Hello", Opcodes. INTEGER, "[Ljava/util/Map;", "java/util/List"}, 0, new Object [] {}); mv. visitFieldInsn (GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv. visitTypeInsn (NEW, "java/lang/StringBuilder"); mv. visitInsn (DUP); mv. visitLdcInsn (">>>>>>>>> testMapList> list. size = "); mv. visitMethodInsn (INVOKESPECIAL, "java/lang/StringBuilder ","
"," (Ljava/lang/String;) V ", false); mv. visitVarInsn (ALOAD, 3); mv. visitMethodInsn (INVOKEINTERFACE, "java/util/List", "size", "() I", true); mv. visitMethodInsn (INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(I) Ljava/lang/StringBuilder;", false); mv. visitMethodInsn (INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "() Ljava/lang/String;", false); mv. visitMethodInsn (INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;) V", false); Label l8 = new Label (); mv. visitLabel (l8); mv. visitVarInsn (ALOAD, 3); mv. visitInsn (ARETURN); Label A9 = new Label (); mv. visitLabel (A9); mv. visitMaxs (4, 8); mv. visitEnd ();} cw. visitEnd (); return cw. toByteArray ();}/*** generate and save the class file ** @ param args * @ author SHANHY * @ create February 3, 2016 */public static void main3 (String [] args) {try {byte [] data = generatorHelloClass (); File file = new File ("H:/Hello. class "); FileOutputStream fos = new FileOutputStream (file); fos. write (data); fos. close ();} catch (Exception e) {e. printStackTrace () ;}/ *** AOP test *** @ param args * @ author SHANHY * @ create February 3, 2016 */public static void main (String [] args) {try {byte [] data = generatorHelloClass (); ClassWriter cw = new ClassWriter (0); ClassReader cr = new ClassReader (data); cr. accept (new AopClassAdapter (ASM5, cw), ClassReader. SKIP_DEBUG); data = cw. toByteArray (); MyClassLoader myClassLoader = new MyClassLoader (); Class
HelloClass = myClassLoader. defineClass ("com. shanhy. demo. asm. hello. hello ", data); Object obj = helloClass. newInstance (); Method method = helloClass. getMethod ("display", null); method. invoke (obj, null); method = helloClass. getMethod ("testList", null); Object result = method. invoke (obj, null); System. out. println (result); Class
StuClass = Thread. currentThread (). getContextClassLoader (). loadClass ("com. shanhy. demo. asm. example. studentServiceImpl "); obj = stuClass. newInstance (); method = stuClass. getMethod ("print", String. class); System. out. println (method. invoke (obj, "single");} catch (Exception e) {e. printStackTrace ();}}}
Package com. shanhy. demo. asm. hello; import org. objectweb. asm. opcodes;/*** custom ClassLoader ** @ author single redwoo (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create February 2, 2016 */public class MyClassLoader extends ClassLoader implements Opcodes {public MyClassLoader () {super ();} public MyClassLoader (ClassLoader parent) {super (parent);} @ Override public Class
LoadClass (String name) throws ClassNotFoundException {return super. loadClass (name);} public Class
DefineClass (String name, byte [] B) {return super. defineClass (name, B, 0, B. length );}}
Finally, this is the source code prototype of the dynamic Hello class.
Package com. shanhy. demo. asm. hello; import java. util. arrayList; import java. util. list; import java. util. map; public class Hello {// declare a constant public static final String FLAG = "I am a constant"; // common method public void display () {for (int I = 0; I <8; I ++) {System. out. println (">>>>>>>>>>" + FLAG) ;}// public List with List returned values
TestList () {List
List = new ArrayList <> (); list. add ("Tome"); list. add ("Jack"); list. add ("Lily"); System. out. println (">>>>>>>>> testList> list. size = "+ list. size (); return list;} // return value of the generic type, which includes two parameters: List and Map //. The parameter is the public List parameter of the Map dynamic parameter.
> TestMapList (boolean val, Map
... Map) {List
> List = new ArrayList <> (); if (val) {for (Map
M: map) {list. add (m) ;}} System. out. println (">>>>>>>>>> testMapList> list. size = "+ list. size (); return list ;}}
For reference only, refer to the official documentation for the asm api. You can use the bytecode Eclipse plug-in to understand what it is.
In actual projects, we generally do not need to use bytecode to generate classes, which will be used only when there are special requirements.
It is said that "not commonly used things solve uncommon problems.