2009-11-24 110 views
1

我怎樣才能動態地加載Java中的類,這兩個參數是類文件的絕對文件路徑以及我希望調用的方法的名稱?java動態類加載器

例如路徑:C:\讓Foo.class 方法:打印()

我在基本作爲簡單的CMD行工具,只是感興趣。代碼示例將不勝感激。

乾杯騙局

回答

2

退房this example

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

在此之後,你可以做這樣的事情,首先創建一個使用默認的構造函數和調用方法「打印」不帶參數的新instace:

Object object = cls.newInstance(); 
cls.getMethod("print").invoke(object); 
5

使用URLClassLoader。該方法的名稱是無關緊要的。您必須將包的根目錄傳遞給類加載器。然後,您可以使用Class.forName()中的全限定類名稱(包+類名稱)獲取Class實例。你可以使用普通的反射調用來創建這個類的一個實例並調用它的方法。

爲了讓你的生活更簡單,看看commons-beanutils。它使得調用方法變得更加簡單。