Why does .class not invoke the static block in a Class?
<p>This is the code I have:</p>

<pre><code>public class StupidClass {
    static {
        System.out.println("Stupid class loaded!");
    }
}
</code></pre>

<p>And the tests I have, which I run <strong>separately</strong>.</p>

<pre><code>import org.junit.Test;

public class StupidTest {
    @Test
    public void foo() throws ClassNotFoundException {
        final Class&lt;?&gt; stupidClass = Class.forName("StupidClass");
        System.out.println(stupidClass.getSimpleName());
    }

    @Test
    public void bar() throws ClassNotFoundException {
        final Class&lt;StupidClass&gt; stupidClassClass = StupidClass.class;
        System.out.println(stupidClassClass.getSimpleName());
    }
}
</code></pre>

<p>When I run test <strong>foo</strong> I will see:</p>

<pre><code>Stupid class loaded!
StupidClass
</code></pre>

<p>But when I run the test <strong>bar</strong> all I see is:</p>

<pre><code>StupidClass
</code></pre>

<p>Quoting from <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html" rel="nofollow noreferrer">this</a> page..</p>

<blockquote>
  <p>Class objects are constructed automatically by the Java Virtual
  Machine as classes are loaded and by calls to the defineClass method
  in the class loader.</p>
</blockquote>

<p>So my understanding is, in test bar, Stupid class is loaded, otherwise I would have seen a null I guess? So Class object is created because class itself is loaded..</p>

<p>And now quoting from <a href="https://stackoverflow.com/questions/9130461/when-is-the-static-block-of-a-class-executed">this</a> page  </p>

<blockquote>
  <p>Static initialization blocks are run when the JVM (class loader - to
  be specific) loads StaticClass (which occurs the first time it is
  referenced in code).</p>
</blockquote>

<p>So I am expecting to see the "Stupid class loaded!" text in test bar as well, but I am not.</p>

<p>Also quoting from <a href="https://rads.stackoverflow.com/amzn/click/com/0131872486" rel="nofollow noreferrer" rel="nofollow noreferrer">Thinking in Java</a></p>

<blockquote>
  <p>Each of the classes Candy, Gum, and Cookie has a static clause that is
  executed as the class is loaded for the first time.</p>
</blockquote>

<p>which is not very accurate it seems..</p>

<p>What am I missing?</p>