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

THEBEST 2010-11-07 01:47:38
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呢?
...全文
45 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
THEBEST 2010-11-07
  • 打赏
  • 举报
回复
Class.forname("test.TestClass");

会先看是否已经加载了该类,如果已经加载则返回已经加载的类,否则重新加载。
houjin_cn 2010-11-07
  • 打赏
  • 举报
回复
Class.forName工作的方式是, 如果类已经存在,则返回存在的那个类, 不存在才从文件加载, 所以你每次得到的是同一个Class;

你可以每次新建一个ClassLoader, 用新的ClassLoader去重新加载类, 这样就可以每次得到不一样的Class

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧