集册 Java实例教程 重新启动Jar应用程序

重新启动Jar应用程序

欢马劈雪     最近更新时间:2020-01-02 10:19:05

564
重新启动Jar应用程序
//来 自 n o w j a v a . c o m

//package com.nowjava;

import java.io.IOException;

import java.lang.management.ManagementFactory;

import java.util.List;


public class Main {

    public static void restartApplication(Runnable runBeforeRestart)

            throws IOException {

        try {

            String java = System.getProperty("java.home") + "/bin/java";

            List<String> vmArguments = ManagementFactory.getRuntimeMXBean()

                    .getInputArguments();

            StringBuffer vmArgsOneLine = new StringBuffer();


            for (String arg : vmArguments) {

                if (!arg.contains("-agentlib")) {

                    vmArgsOneLine.append(arg);

                    vmArgsOneLine.append(" ");

                }

            }
            /** from 
            时   代     Java  公  众  号 - nowjava.com**/


            final StringBuilder cmd = new StringBuilder("\"" + java + "\" "

                    + vmArgsOneLine);


            String javaCommand = System.getProperty("sun.java.command");


            if (javaCommand.endsWith(".jar")) {

                cmd.append("-jar \"").append(javaCommand).append("\"");

            } else {

                cmd.append("-cp \"")

                        .append(System.getProperty("java.class.path"))

                        .append("\" ").append(javaCommand);

            }


            Runtime.getRuntime().addShutdownHook(new Thread() {

                @Override

                public void run() {

                    try {

                        Runtime.getRuntime().exec(cmd.toString());

                    } catch (IOException e) {

                        e.printStackTrace();

     
展开阅读全文