每次調用我的方法時,我都想創建一個新的ClassLoader
。創建新的ClassLoader以重新加載類
因此,我可以在不退出程序的情況下重新加載class
。
如何更新由ClassLoader
加載的class
也是一個解決方案。
我該如何做到這一點?
每次調用我的方法時,我都想創建一個新的ClassLoader
。創建新的ClassLoader以重新加載類
因此,我可以在不退出程序的情況下重新加載class
。
如何更新由ClassLoader
加載的class
也是一個解決方案。
我該如何做到這一點?
我找到了一個好解釋的答案在這裏:
http://www.exampledepot.com/egs/java.lang/reloadclass.html
重要的是有兩個二進制文件夾,在我的情況: 一個用於測試案例,一個是節目源。
報價:
URL[] urls = null;
try {
// Convert the file object to a URL
File dir = new File(System.getProperty("user.dir")
+File.separator+"dir"+File.separator);
URL url = dir.toURL(); // file:/c:/almanac1.4/examples/
urls = new URL[]{url};
} catch (MalformedURLException e) {
}
try {
// Create a new class loader with the directory
ClassLoader cl = new URLClassLoader(urls);
// Load in the class
Class cls = cl.loadClass("MyReloadableClassImpl");
只需添加 - 此解決方案僅適用於重新加載的類沒有任何方法刪除/新類引用的情況。這種方法的問題是,如果有人首先添加依賴類,可能會創建NoClassDefFoundError。最好的辦法是在沒有完全停止應用程序的情況下重新加載所有類。 – ha9u63ar 2018-01-10 10:18:53
看到這個? ClassLoader Load/Reload Example
我認爲這個博客可以滿足您的需求。
我加載一個帶有loadClass(「string」)的JavaCompiler源代碼編譯類,然後用JUnitCore運行這個類。之後,我編輯* .java中的源代碼,使用JavaCompiler進行編譯並重新加載。 – ctekk 2012-03-22 09:32:06
一個很好的用例有趣的問題。 +1 – 2012-03-22 09:53:31