如何在運行時動態加載JAR?為什么在Java中這么難呢?如果您想擁有任何類型的模塊系統,則需要能夠動態加載JAR。我聽說有辦法寫你自己的ClassLoader但是,對于一些應該(至少在我看來)應該像調用一個包含JAR文件的方法一樣簡單的方法來說,這需要做大量的工作。對于這樣做的簡單代碼有什么建議嗎?
4 回答

寶慕林4294392
TA貢獻2021條經驗 獲得超8個贊
URLClassLoader child = new URLClassLoader( new URL[] {myJar.toURI().toURL()}, this.getClass().getClassLoader());Class classToLoad = Class.forName("com.MyClass", true, child); Method method = classToLoad.getDeclaredMethod("myMethod");Object instance = classToLoad.newInstance(); Object result = method.invoke(instance);

蝴蝶刀刀
TA貢獻1801條經驗 獲得超8個贊
下面的解決方案是惡意的,因為它使用反射繞過封裝,但是它工作得完美無缺:
File file = ...
URL url = file.toURI().toURL();
URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(classLoader, url);
添加回答
舉報
0/150
提交
取消