我最近发表了一篇在运行时更新 Java 代码的帖子,经过几个小时摆弄不同的示例代码和阅读教程后,我遇到了以下问题:
通过使用 ClassLoader,我能够在运行时使用http://www.exampledepot.com/egs/java.lang/reloadclass.html上的代码将本地变量从 Class 更改MyVar1
为 Class ,但我无法替换该类与另一个版本的.MyVar2
MyVar2
MyVar2
两者都MyVar1
实现MyVar2
了一个接口VarInterface
。主类使用 type 保存变量的实例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()
被调用 ad infinitum,即使我替换了MyVar2.class
和MyVar2.java
文件。