使用ASM操作Java位元組碼,實現AOP原理

來源:互聯網
上載者:User

使用ASM操作Java位元組碼,實現AOP原理

本文通過一個的例子來實現:使用ASM動態產生Java位元組碼檔案(.class) 或者 載入位元組碼後動態修改位元組碼,添加我們需要執行的代碼,來類比實現Spring AOP。

年底了,也沒心情摳字了,把寫demo包含的幾個類代碼直接貼出來吧,代碼拷貝下來後可以直接使用,不會有什麼其他錯誤。
使用 asm-5.0.3.jar
demo工程的package為com.shanhy.demo.asm.hello

5個Java檔案:
AopClassAdapter.java 用來處理哪些方法需要進行修改
AopInteceptor.java 要修改的方法中,準備添加的我們自己的代碼邏輯
AopMethodVisitor.java 修改位元組碼
HelloGeneratorClass.java 通過asm動態產生java類,測試的main方法也在這裡
MyClassLoader.java 自訂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);        // 對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", false);    }    @Override    public void visitInsn(int opcode) {        if (opcode >= IRETURN && opcode <= RETURN)// 在返回之前安插after 代碼。            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;/** * 通過ASM產生類的位元組碼 *  * @author Administrator * */public class HelloGeneratorClass implements Opcodes {    /**     * 使用構造Hello類class位元組碼     * package中的Hello.java只是代碼原型,本例中只供對比用,沒有實際使用到這個類。     * ASM代碼產生工具使用 bytecode     *     * @return     * @throws Exception     * @author SHANHY     * @create 2016年2月3日     */    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 l9 = new Label();            mv.visitLabel(l9);            mv.visitMaxs(4, 8);            mv.visitEnd();        }        cw.visitEnd();        return cw.toByteArray();    }    /**     * 產生儲存class檔案     *     * @param args     * @author SHANHY     * @create 2016年2月3日     */    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測試     *     * @param args     * @author SHANHY     * @create  2016年2月3日     */    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, "單單"));        } catch (Exception e) {            e.printStackTrace();        }    }}
package com.shanhy.demo.asm.hello;import org.objectweb.asm.Opcodes;/** * 自訂ClassLoader * * @author   單紅宇(365384722) * @myblog  http://blog.csdn.net/catoop/ * @create    2016年2月2日 */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);    }}

最後這個是我們動態產生的Hello類的源碼原型。

package com.shanhy.demo.asm.hello;import java.util.ArrayList;import java.util.List;import java.util.Map;public class Hello {    // 聲明 一個常量    public static final String FLAG = "我是常量";    // 普通方法    public void display(){        for (int i = 0; i < 8; i++) {            System.out.println(">>>>>>>>>>" + FLAG);        }    }    // 帶有List傳回值    public List testList(){        List list = new ArrayList<>();        list.add("Tome");        list.add("Jack");        list.add("Lily");        System.out.println(">>>>>>>>>>testList > list.size = " + list.size());        return list;    }    // 泛型傳回值,包含List和Map    // 兩個參數,參數為Map動參    public List> 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;    }}

僅供參考,關於ASM的API看看官方文檔即可。bytecode這個Eclipse外掛程式大家可以用一下,用了你就知道是幹什麼的了。
實際項目中一般不需要我們去用位元組碼來產生類,只有在特殊需求的時候才會使用。
話說“不常用的東西解決不常見的問題”嘛。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.