Can I use main() to restart my application?

Adesh picture Adesh · Nov 1, 2012 · Viewed 20.8k times · Source

I am researching a way to restart my java application by clicking a button on the GUI. I searched the web and came across main( new String[0]). I need to understand if this is an valid way to restart my application. Can someone please advise thanks.

private void bnNewsaleActionPerformed(java.awt.event.ActionEvent evt) {

    main( new String[0]);
    }

Edit Would this be better?

private void bnNewsaleActionPerformed(java.awt.event.ActionEvent evt) {
    classname.this.dispose();
    main( new String[0]);
    }

Answer

Jon Skeet picture Jon Skeet · Nov 1, 2012

It calls the static main method with an empty string array. See if this makes it any clearer:

String[] args = new String[0]; // Or String[] args = {};
main(args);

Admittedly it's unusual to call a main method from non-main method... and this won't really "restart" the application. It will call it from within your existing handler which may well have nasty consequences. I wouldn't recommend it.

If you can work out a way to start an entirely clean process, that would be a far more reliable "restart".