在运行时加载Java-Byte-Code

时间:2010-07-04 11:06:39

标签: java classloader bytecode

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

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

谢谢!

2 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分:2)

如果字节代码不在正在运行的程序的类路径中,则可以使用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) {
}