2011-05-08 54 views

回答

2

裝入類內容轉換成一個字節數組,手動使用ClassLoader.html#defineClass(java.lang.String, byte[], int, int)

+3

你必須加載任何依賴手工爲好。另一種方法是創建一個包含所需類的新URLClassLoader。 – 2011-05-08 07:26:58

+0

我想加載一個包中相互依賴的所有類。我可以用這種方式加載班級嗎? – reflector 2011-05-08 07:45:02

6

實施例從here採取:

// 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) { 
}