【发布时间】:2010-06-20 20:48:34
【问题描述】:
我最近发了一个帖子Update Java code during runtime,经过几个小时摆弄不同的示例代码和阅读教程后,我遇到了以下问题:
通过使用 ClassLoader,我能够在运行时使用 http://www.exampledepot.com/egs/java.lang/reloadclass.html 处的代码将本地变量从 Class MyVar1 更改为 Class MyVar2,但我无法用另一个替换该 Class MyVar2 MyVar2 的版本。
MyVar1 和 MyVar2 都实现了一个接口 VarInterface。主类使用VarInterface 类型保存变量的实例。
我已经阅读了其他几个声称是正确的实现,但我无法让它工作。谁能看到我在这里做错了什么?
主类循环:
while(true){
i++;
Thread.sleep(1000);
ui.ping();
if(i > 3)
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()打印“Hello”,当i==10您将课程更改为打印“再见”时,您的问题是您仍然看到“Hello”不管怎么改,对吧? -
那种。我没有用另一个版本(例如 i == 10)替换 MyVar2 的内部触发器,我只是直接替换文件或在 eclipse 中编辑并保存。
标签: java class classloader reloading