我最近發了一個帖子Update Java code during runtime過了幾個小時,不同的例子代碼,閱讀教程左右擺弄我遇到了以下問題重裝代碼:Java的問題,使用的ClassLoader
通過使用一個ClassLoader我已經能夠在運行時使用代碼http://www.exampledepot.com/egs/java.lang/reloadclass.html將類別MyVar1
中的局部變量從類MyVar1
更改爲類MyVar2
,但我一直無法用MyVar2
的另一個版本替換該類MyVar2
。
MyVar1
和MyVar2
都實現了接口VarInterface
。主類使用VarInterface
類型保存變量的一個實例。
我讀過幾個其他聲稱是正確的實現,但我無法得到這個工作。任何人都可以看到我在這裏做錯了嗎?
主類的循環:
while(true){
i++;
Thread.sleep(1000);
ui.ping();
if(i > 3)
replaceVar();
}
replaceVar:
ClassLoader parentClassLoader = MyClassLoader.class.getClassLoader();
MyClassLoader classLoader = new MyClassLoader(parentClassLoader);
Class newClass = classLoader.loadClass("MyVar2");
ui = (VarInterface)newClass.newInstance();
MyClassLoader.loadClass:
public Class<?> loadClass(String what){
// Get the directory (URL) of the reloadable class
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();
urls = new URL[]{url};
} catch (MalformedURLException e) {
}
// Create a new class loader with the directory
ClassLoader cl = new URLClassLoader(urls);
// Load in the class
Class cls = null;
try {
cls = cl.loadClass("MyVar2");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return cls;
}
對於第3次迭代MyVar1.ping()
被調用時,該MyVar2.ping()
被稱爲廣告後無限,即使我替換MyVar2.class
和MyVar2.java
文件。
只是要清楚的問題 - 讓我們說'MyVar2.ping()'打印'你好',當'i == 10'你改變類打印'再見',你的問題是,你仍然看到'你好'不管改變什麼,對吧? – RonK 2010-06-20 21:09:00
種類。我沒有用另一個版本替換MyVar2的內部觸發器(例如i == 10),我只是直接替換文件或在eclipse中編輯並保存。 – Glader 2010-06-20 21:28:41