title: "$0 (Program Name) in Java? Discover main class?" again
body: <p>I have found following question:
  <a href="https://stackoverflow.com/questions/41894/0-program-name-in-java-discover-main-class">$0 (Program Name) in Java? Discover main class?</a>
  but accepted answer fails in this situation:</p>
  
  <pre><code>public class Derived extends Base { }
  
  class Base {
      public static void main(String[] args){
          System.out.println(getTheClassName());
      }
  
      static String getTheClassName(){
          StackTraceElement[] stack = Thread.currentThread().getStackTrace();
          StackTraceElement main = stack[stack.length - 1];
          return main.getClassName();
      }
  }
  </code></pre>
  
  <p>When calling:</p>
  
  <pre><code>java Derived
  </code></pre>
  
  <p>the output is unfortunately <code>Base</code> not <code>Derived</code> as expected.</p>
  
  <p>Is it possible to get the name of <em>real</em> main class? (btw. <code>jps</code> tool detects main class correctly but to get the proper name I need to know ID of current VM, and that is also a problem)</p>
  
  <p>Best regards.</p>
  
  <p><strong>Edit:</strong> to be precise: I need to know what is the name of class passed as command line argument passed to JVM. <code>jps</code> tools does it the way I want, but I cannot use this tool because of other problems (such as unknown VMid).</p>
  
  <p><strong>Edit2:</strong> replying globally to <strong>Thorbjørn's</strong> answer:</p>
  
  <blockquote>
    <p>For your approach to work, you need to have a non-static method instead. Make it
    non-static, have a main() in Derived doing a new Derived().getTheClassName()</p>
  </blockquote>
  
  <p>I am wondering I can get the name without implementing main method in Derived class.</p>
  
  <p><strong>Solution:</strong> I will provide both (Thorbjørn's and erickson's) mechanisms of an initialization of <code>Derived</code> class ;-) All of the answers were very helpful. I accepted Thorbjørn's becase he posted his answer earlier than erickson. Thank You.</p>