一個通不過Java位元組碼校正的例子

來源:互聯網
上載者:User

一般我們寫Java源碼,用Java編譯器編譯出.class檔案,是不會碰到校正失敗的狀況的,因為正常的 Java編譯器都會小心對待產生的程式碼。所以,想要看到校正失敗的狀況,很容易的一個辦法就是自己產生 不合法的位元組碼。

這裡我用了ObjectWeb的ASM來產生位元組碼。可以從官網下載asm-3.1.jar,並保證其在編譯和運行下面 這個程式時在classpath上。

(本來是很想順便試試Charles O. Nutter寫的bitescript庫,不過惰性上來了,懶得去下載……下次 吧,下次)

Java代碼

import java.io.FileOutputStream;import org.objectweb.asm.ClassWriter;import org.objectweb.asm.MethodVisitor;import org.objectweb.asm.Opcodes;public class TestASM implements Opcodes {    public static void main(String[] args) throws Exception {        ClassWriter cw = new ClassWriter(0);        cw.visit(            V1_5,               // class format version            ACC_PUBLIC,         // class modifiers            "TestVerification", // class name fully qualified name            null,               // generic signature            "java/lang/Object", // super class fully qualified name            new String[] { }    // implemented interfaces        );                MethodVisitor mv = cw.visitMethod(            ACC_PUBLIC, // access modifiers            "foo",      // method name             "()V",     // method description             null,      // generic signature             null       // exceptions        );        mv.visitCode();        mv.visitInsn(FCONST_0);        mv.visitVarInsn(FSTORE, 1);        mv.visitVarInsn(ILOAD, 1);        mv.visitVarInsn(ISTORE, 1);        mv.visitInsn(RETURN);        mv.visitMaxs(1, 2);        mv.visitEnd(); // end method                cw.visitEnd(); // end class                byte[] clz = cw.toByteArray();        FileOutputStream out = new FileOutputStream("TestVerification.class");        out.write(clz);        out.close();    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.