在运行时加载Java字节码 [英] Load Java-Byte-Code at Runtime
问题描述
我得到了一些在程序中生成的Java字节码(因此是经过编译的Java源代码)。现在,我想将此字节代码加载到当前运行的Java-VM中并运行特定功能。我不确定如何做到这一点,我对Java类加载器进行了深入研究,但未找到直接方法。
I got some java-byte-code (so compiled java-source) which is generated in my program. Now I want to load this byte-code into the currently running Java-VM and run a specific function. I'm not sure how to accomplish this, I digged a little bit into the Java Classloaders but found no straight way.
我找到了一个使用类文件的解决方案在硬盘上,但是我得到的字节码在字节数组中,我不想将其写入磁盘,而是直接使用它。
I found a solution which takes a class-file on the harddisk, but the bytecode I got is in a Byte-Array and I dont want to write it down to the disk but use it directly instead.
谢谢! / p>
Thanks!
推荐答案
您需要编写一个自定义的类加载器,该类加载器会使findClass方法超载
you need to write a custom class loader that overloads the findClass method
public Class findClass(String name) {
byte[] b = ... // get the bytes from wherever they are generated
return defineClass(name, b, 0, b.length);
}
这篇关于在运行时加载Java字节码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!