2010-07-04 54 views
7

我得到了一些在我的程序中生成的java-byte-code(如此编译的java-source)。现在我想将这个字节码加载到当前运行的Java-VM中并运行一个特定的函数。我不确定如何实现这一点,我对Java Classloaders进行了一些探索,但没有找到直接的方法。在运行时加载Java-Byte-Code

我发现了一个解决方案,它在硬盘上取得一个类文件,但是我得到的字节码在Byte-Array中,我不想将它写到磁盘上,而是直接使用它。

谢谢!

+0

我觉得这个环节下,你会发现你在找什么:HTTP://tutorials.jenkov。 com/java-reflection/dynamic-class-loading-reloading.html查看最后一节“ClassLoader Load/Reload Example”。 – 2010-07-04 11:23:00

+0

我的问题有点不清楚:我没有一个类文件,但一个字节数组,我想直接加载它。不管怎么说,还是要谢谢你! – theomega 2010-07-04 13:04:20

+0

而且我很确定我的链接正好提供了。至少我通过它找到了这个:http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ClassLoader.html#defineClass(byte [],int,int) 你也可以显然总是将你的字节数组保存到一个临时目录。 – 2010-07-04 15:06:10

回答

9

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

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

谢谢,听起来像是一种方式,但没有直接的方式,没有编写一个custon ClassLoader? – theomega 2010-07-04 13:05:05

+0

至少目前为止我还没有找到 – 2010-07-04 13:12:56

+0

工作得很好,谢谢! – theomega 2010-07-04 14:43:03

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) { 
} 
+0

我的问题有点不清楚:我没有一个类文件,但一个字节数组,我想直接加载它。不管怎么说,还是要谢谢你! – theomega 2010-07-04 13:04:27

+0

随意编辑您的问题更加精确。引用的代码与硬盘上的类文件一起使用。 – 2010-07-04 14:37:37