Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: how to "restart" a static class?
    text
    copied!<p>I have a static class (Foo) and a main class (Main)</p> <p>See Main.java:</p> <pre><code>public class Main { public static void main(String[] args) { System.out.println(Foo.i); // 0 Foo.i++; System.out.println(Foo.i); // 1 // restart Foo here System.out.println(Foo.i); // 1 again...I need 0 } } </code></pre> <p>See Foo.java:</p> <pre><code>public class Foo { public static int i = 0; } </code></pre> <p>Is there any way to restart or reset a static class?</p> <p>Note: I need this because I'm testing a static class with jUnit and I need to clean parameters before second test.</p> <hr> <p>EDIT</p> <p><strong>ALMOST SOLUTION:</strong></p> <p>Using StanMax answer, I can to this:</p> <p><strong>Main.java</strong></p> <pre><code>public class Main { public static void main(String[] args) throws Exception { test(); test(); } public static void test() throws Exception { System.out.println("\ntest()"); MyClassLoader myClassLoader = new MyClassLoader(); Class&lt;?&gt; fooClass = myClassLoader.loadClass(Foo.class.getCanonicalName()); Object foo = fooClass.newInstance(); System.out.println("Checking classloader: " + foo.getClass().getClassLoader()); System.out.println("GC called!"); System.gc(); } } </code></pre> <p><strong>MyClassLoader.java</strong></p> <pre><code>public class MyClassLoader { private URLClassLoader urlClassLoader; public MyClassLoader() { try { URL url = new File(System.getProperty("user.dir") + "/bin/").toURL(); URL[] urlArray = {url}; urlClassLoader = new URLClassLoader(urlArray, null); } catch (Exception e) { } } public Class&lt;?&gt; loadClass(String name) { try { return (Class&lt;?&gt;) urlClassLoader.loadClass(name); } catch (Exception e) { } return null; } @Override protected void finalize() throws Throwable { System.out.println("MyClassLoader - End."); } } </code></pre> <p><strong>Foo.java</strong></p> <pre><code>public class Foo { public static int i = 0; static { System.out.println("Foo - BEGIN ---------------------------------"); } public void finalize() throws Throwable { System.out.println("Foo - End."); } } </code></pre> <p><strong>OUTPUT</strong></p> <pre><code>test() Foo - BEGIN --------------------------------- Checking classloader: java.net.URLClassLoader@ec160c9 GC called! MyClassLoader - End. Foo - End. test() Foo - BEGIN --------------------------------- Checking classloader: java.net.URLClassLoader@ec3fb9b GC called! MyClassLoader - End. Foo - End. </code></pre> <p><strong>PROBLEM:</strong> if I do the cast bellow:</p> <pre><code>Foo foo = (Foo) fooClass.newInstance(); </code></pre> <p>I get error:</p> <pre><code>java.lang.ClassCastException </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload