动态更新类,为何行不通?

THEBEST THEBEST 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
public class TestReloadClass {
private static long startTime = System.currentTimeMillis();

public static Class reloadClass(Class cls) throws Exception {
String path = cls.getResource(cls.getSimpleName() + ".class").getPath();
File file = new File(path);
if (file.exists()) {
System.out.println("file:" + path);
System.out.println("start:" + startTime);
System.out.println("modif:" + file.lastModified());
if (file.lastModified() > startTime) {
System.out.println("reload new class:" + cls.getName());
return Class.forName(cls.getName());
}
}
return null;
}

/**
* @param args
*/
public static void main(String[] args) throws Exception {
Map m = new HashMap();
m.put(TestHotThread.class.getName(), TestHotThread.class);
while (true) {
Set entrys = m.entrySet();
Iterator iter = entrys.iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
Class cls = (Class)(entry.getValue());
Thread t = (Thread)cls.newInstance();
t.start();
Thread.sleep(10000);
if ((cls = reloadClass(cls)) != null)
entry.setValue(cls);
}
}
}
}
public class TestHotThread extends Thread {

public void run() {
System.out.println("thread is runni..");
try {
this.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

}

}
类重新用Class.forName生成了class,重新放在map中,为什么下一次运行的还是老的class呢?
...全文

相关推荐

评论 2
收藏 已收藏
分享
返回顶部
THEBEST
Java SE 62,621 成员 307,251 内容