在运行时加载Java-Byte-Code

我得到了一些在我的程序中生成的java-byte-code(如此编译的java-source)。 现在我想将这个字节码加载到当前运行的Java-VM中并运行一个特定的函数。 我不知道如何实现这一点,我在Java类加载器中挖掘了一点,但没有找到直接的方法。

我找到了一个解决方案,它在硬盘上采用了一个类文件,但是我得到的字节码是在字节数组中,我不想把它写到磁盘上而是直接使用它。

谢谢!

你需要编写一个重载findClass方法的自定义类加载器

public Class findClass(String name) { byte[] b = ... // get the bytes from wherever they are generated return defineClass(name, b, 0, b.length); } 

如果字节代码不在正在运行的程序的类路径中,则可以使用URLClassLoader。 来自http://www.exampledepot.com/egs/java.lang/LoadClass.html

 // Create a File object on the root of the directory containing the class file File file = new File("c:\\myclasses\\"); try { // Convert File to a URL URL url = file.toURL(); // file:/c:/myclasses/ URL[] urls = new URL[]{url}; // Create a new class loader with the directory ClassLoader cl = new URLClassLoader(urls); // Load in the class; MyClass.class should be located in // the directory file:/c:/myclasses/com/mycompany Class cls = cl.loadClass("com.mycompany.MyClass"); } catch (MalformedURLException e) { } catch (ClassNotFoundException e) { }