[英]Dynamically load a JAR using URLClassLoader?
我有一個程序需要能夠在運行時動態加載 JAR - 環顧四周后,我相信它使用了 URLClassLoader,但我不確定如何讓它工作。 JAR“openup.jar”與程序位於同一目錄中。
理想情況下,我希望能夠加載這個 JAR,而不必在其中指定每個單獨的類。
我成功使用了什么:
@SuppressWarnings("unchecked")
public void addURL(URL u) throws IOException {
URLClassLoader sysLoader = (URLClassLoader) ThisClass.class.getClassLoader();
URL urls[] = sysLoader.getURLs();
for (int i = 0; i < urls.length; i++) {
if (urls[i].toString().equalsIgnoreCase(u.toString())) {
return;
}
}
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysLoader, new Object[] { u });
} catch (Throwable t) {
throw new IOException("Error, could not add URL to system classloader");
}
}
在運行時如何動態加載Jars中確實提供了幾乎相同的解決方案?
這里我解釋一下創建jar然后在另一個項目中動態加載jar的全過程:
創建jar的步驟:
包 newJar.com.example;
公共類 MyClass {
public MyClass() {
// TODO Auto-generated constructor stub
}
public void helloWorld() {
System.out.println("Hello from the helloWorld");
}
}
動態加載jar的步驟:
創建一個新項目並添加以下代碼:
公共類自定義類{
public CustomClass() { // TODO 自動生成的構造函數存根 }
公共無效getCall(文件myJar){
try { URLClassLoader loader = new URLClassLoader(new URL[] { myJar.toURI().toURL() }, CustomClass.class.getClass().getClassLoader()); Class classToLoad = Class.forName("newJar.com.example.MyClass", true, loader); System.out.println(classToLoad); Method method = classToLoad.getDeclaredMethod("helloWorld"); Object instance = classToLoad.newInstance(); Object result = method.invoke(instance); } catch (MalformedURLException | ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); }
}
public static void main(String[] args) { // TODO 自動生成的方法存根
File myJar = new File("Path of your jar ");//"D:\\\\ECLIPSE\\\\myjar.jar" CustomClass cls = new CustomClass(); cls.getCall(myJar);
}
}
這就是它如何使用 jar 的方式,如果 jar 在服務器上,則可以提供服務器路徑而不是本地路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.