title: Looking for a way to re-run class static initializers
body: <p>Is there a way to return a non-core Java class to a freshly loaded state?  I want the equivalent of unloading a class and reloading it from scratch.  I'm mostly concerned with static initializers and variables.</p>
  
  <p>Problem context: I'm writing a robo-grader for student code.  One common student error I've seen is to use static variables inappropriately.  E.g., consider a Collection with a static count of elements it contains.  The collection will work fine the first time it is created and used, but fail on the next instantiation.  If I want my tests to be as modular as possible, I need a way to restore clean state after a test.</p>
  
  <p>Right now I'm loading the Class more or less like this, and I've sketched how I want to use it.</p>
  
  <pre><code>    String classUnderTest = "package.class";
      Class unitUnderTest;
      try {
          unitUnderTest = Class.forName(classUnderTest);
      } catch (ClassNotFoundException e) {
          System.out.println("Class \"" + classUnderTest + "\" was not found, can't continue.");
          printGradeAndExit();
      }
      // Run foundation tests (stuff on which later tests depend) using unitUnderTest.newInstance()
      runFoundationTests(unitUnderTest);
      // Now reset unitUnderTest for a static variable detection test
      lookForCommonStaticVariableMistakes(unitUnderTest);
  </code></pre>
  
  <p>Obviously, robo-graders can't be perfect, but I'd like to catch the common errors, and this is one of them.</p>
  
  <p>According to the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.7" rel="nofollow">Java Language Specification, Section 12.7</a>, supporting unloading of classes is optional (but would do exactly what I want).  Is there any way to do this without relying on non-standard features?</p>
  
  <p>The last resort is to do an Ant build which runs a series of tests in separate programs, but I'd like to make this work in a single process if possible.</p>