2010-07-04 57 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