How to get bytecode as byte array from Class

回眸只為那壹抹淺笑 提交于 2019-11-30 20:50:30

问题


Given an arbitrary Class instance, including one that's runtime generated (no .class file on disk), is there any way to get the class bytes?


回答1:


In general, this is not possible. While loading a class, JVM parses its bytecode and converts it to the internal representation. After that JVM is free to forget the original bytecode, and that's what really happens with HotSpot JVM.

However, with the certain hacks it is possible to inspect the internal class representation and convert it back to a valid class file (though it will differ from the original bytecode). Such process is used in HotSpot JVM to reconstitute a class file for Instrumentation purposes.

As a proof of concept, I've written a program that extracts processed bytecode of a loaded class from JVM memory using Unsafe. This is only for a demo; don't ever try this in production.

EDIT

You can also get class file data (possibly modified by JVM) using Instrumentation API. This requires a Java agent loaded either at VM bootstrap (using -javaagent VM option) or at runtime via Dynamic Attach mechanism.

Here is an example of such agent: GetBytecode.java.

Finally, if you don't mind using native code, there are JVMTI functions GetConstantPool and GetBytecodes to obtain the bytecodes of the particular Java method.

Here is a JVMTI example.




回答2:


String classFile = "/" + Object.class.getName().replace('.', '/') + ".class";
System.out.println(classFile);
URL url = Test.class.getResource(classFile);
System.out.println(url);

produces this output.

/java/lang/Object.class
jar:file:/usr/java/jdk1.8.0_60/jre/lib/rt.jar!/java/lang/Object.class

so you may use url to read in bytes. (not applicable for runtime generated classes)



来源:https://stackoverflow.com/questions/35071016/how-to-get-bytecode-as-byte-array-from-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!