title: Get name of executable jar from within main() method
body: <p>I've created an executable jar and using commons-cli to give the user the ability to specify command line parameters when he launches the client.  Everything works fine.  However, when I print the usage statement for the jar, I would like to show the following:</p>
  
  <pre><code>usage: java -jar myprog.jar &lt;options&gt; &lt;file&gt;
  --help Display the help message
  --debug Enable debugging
  ....
  </code></pre>
  
  <p>Printing of all the options is easily done with commons-cli.  However, the "usage" line is the head scratcher.  I cannot seem to figure out a way to get the "myprog.jar" name from the args[] that are passed to the application.</p>
  
  <p>Is there any easy way of doing this?  I could use a pretty convoluted method to back trace from my class' classloader and figure out if it is contained within a jar, but that seems like a fairly ugly answer to what should be a pretty simple question.</p>
  
  <pre><code>private String getPath(Class cls) {
      String cn = cls.getName();
      String rn = cn.replace('.', '/') + ".class";
      String path =
              getClass().getClassLoader().getResource(rn).getPath();
      int ix = path.indexOf("!");
      if(ix &gt;= 0) {
          return path.substring(0, ix);
      } else {
          return path;
      }
  }
  </code></pre>