重新启动自己 - 我可以重新初始化一切从头开始?
-
25-09-2019 - |
题
我有这样的事情:
public static final String path;
static {
path = loadProperties("config.conf").getProperty("path");
}
public static void main(String... args) {
// ... do stuff (starting threads that reads the final path variable)
// someone want's to update the path (in the config.conf file)
restart(); // ???
}
我要重新初始化JVM调用静态初始化一遍,然后main(...)
!
<强>能不能做到吗
解决方案
您使用自定义的类装载器可以启动应用程序,这将让你加载和卸载你的静态变量。
但是,基本上它是一个非常糟糕的设计需要这样做。我喜欢拍场决赛,但你不应该让他们最终,如果你想改变他们。
其他提示
如果你的目标很简单,就是重新加载一些配置文件,为什么不执行文件更改监视器?
下面是本主题的很好的教程:
http://download.oracle.com/javase/tutorial/必要/ IO / notification.html
我想你求婚(自动重新启动您的应用程序),将是一个不只是看文件的更新稍微麻烦了。
我接受彼得Lawrey 一>答案,但张贴任何人都可以使用一个完整的例子!
我不打算在生产代码中使用这个......有这样做的其他方式!的
public class Test {
public static void main(String args[]) throws Exception {
start();
Thread.sleep(123);
start();
}
private static void start() throws Exception {
ClassLoader cl = new ClassLoader(null) {
protected java.lang.Class<?> findClass(String name)
throws ClassNotFoundException {
try{
String c = name.replace('.', File.separatorChar) +".class";
URL u = ClassLoader.getSystemResource(c);
String classPath = ((String) u.getFile()).substring(1);
File f = new File(classPath);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte buff[] = new byte[(int) f.length()];
dis.readFully(buff);
dis.close();
return defineClass(name, buff, 0, buff.length, null);
} catch(Exception e){
throw new ClassNotFoundException(e.getMessage(), e);
}
}
};
Class<?> t = cl.loadClass("Test$Restartable");
Object[] args = new Object[] { new String[0] };
t.getMethod("main", new String[0].getClass()).invoke(null, args);
}
public static class Restartable {
private static final long argument = System.currentTimeMillis();
public static void main(String args[]) throws Exception {
System.out.println(argument);
}
}
}
一个简单的方法是简单地不的使用静态初始化这一点。为什么不干脆让path
非最终在main
加载它?
这个怎么样结构
public static void main(String... args) {
boolean restart = true;
while (restart )
{
retart = runApplication();
}
}
如果你曾经发现需要重新启动你的应用程序,有runApplication返回true。 如果它是时间退出返回假;
如果你有一个UI或者后台程序,所以你可以控制输出到标准输出,你可以在启动程序外面的包装。
如果在退出时输出节目“重新启动”,您可以再次从该包装重新启动程序。如果不是,它只是结束。
或者,如果你想要的纯Java方式,你可以用类加载器的解决方案彼得Lawrey在他的文章中提到去。在去沿着这条路你真的应该重新考虑你的设计(如果它是你的代码),并能够自我整顿的代码。
不隶属于 StackOverflow