获取Java类的字节码

Java类并没有一个toBytecode之类的函数,不过要获取很简单,因为一个类的字节码就是它的class文件的内容,所以直接读取它,存到一个byte[]里就搞定了。

package test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Test {

    public static byte[] getClassByteCode(String className) {
        String jarname = "/" + className.replace('.', '/') + ".class";
        InputStream is = Test.class.getResourceAsStream(jarname);

        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        byte imgdata[] = null;
        try {
            while ((ch = is.read()) != -1) {
                bytestream.write(ch);
            }
            imgdata = bytestream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bytestream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return imgdata;
    }

    public static void main(String[] args) {
        System.out.println("Bytecode length: " + getClassByteCode("test/Test").length);
    }
}

 

posted @ 2016-02-02 17:30  princessd8251  阅读(792)  评论(0)    收藏  举报