如何使您的Java应用程序自行重启 [英] How to make your java application restarts itself

查看:985
本文介绍了如何使您的Java应用程序自行重启的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中实现 reset 功能,它清理一些目录,复制文件等,然后为了完成我需要重启的过程。

I want to implement reset feature in my application which cleans up some directories, copies files etc. then in order to complete the process I need to restart it.

如何让应用程序重新运行?我认为打开第二个实例并关闭这个实例就足够了,尽管不是真正的重启。

How to make application reruns itself? I think opening second instance and closing this one would be enough, altough it is not real restart.

我的应用程序的核心是类扩展 JFrame 但是有许多静态块在程序执行时读取类的扩展名。我需要以编程方式重新启动我的应用程序,以便再次创建/执行所有静态集合和块。

My application's core is class extending JFrame but there is lot of static blocks which read class's extensions when the program is executed. I need to restart programatically my application so all of the static collection and blocks will be created/executed again.

以这种方式开始。

SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new Window().createGUI();
        }
    });

这似乎工作正常:

public void restart() {
    /*  dispose();
    Window.main(null);*/
    StringBuilder cmd = new StringBuilder();
    cmd.append(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java ");
    for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
        cmd.append(jvmArg + " ");
    }
    cmd.append("-cp ").append(ManagementFactory.getRuntimeMXBean().getClassPath()).append(" ");
    cmd.append(Window.class.getName()).append(" ");

    try {
        Runtime.getRuntime().exec(cmd.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.exit(0);
}


推荐答案

这是来自其他话题但与其他主题中接受的问题相反,这个问题确实有效。

This is from the other topic but in the opposite to the accepted question in this other topic this one really works.

public void restart() {
          StringBuilder cmd = new StringBuilder();
            cmd.append(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java ");
            for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
                cmd.append(jvmArg + " ");
            }
            cmd.append("-cp ").append(ManagementFactory.getRuntimeMXBean().getClassPath()).append(" ");
            cmd.append(Window.class.getName()).append(" ");

            try {
                Runtime.getRuntime().exec(cmd.toString());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.exit(0);
    }






27 / 02/2018:我相信Mark发布了更好的解决方案: https://stackoverflow.com/a/48992863/1123020


27/02/2018: I believe that Mark posted better solution: https://stackoverflow.com/a/48992863/1123020

这篇关于如何使您的Java应用程序自行重启的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆