KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have a static class (Foo) and a main class (Main) See Main.java: 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 } } See Foo.java: public class Foo { public static int i = 0; } Is there any way to restart or reset a static class? Note: I need this because I'm testing a static class with jUnit and I need to clean parameters before second test. EDIT ALMOST SOLUTION: Using StanMax answer, I can to this: Main.java 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<?> 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(); } } MyClassLoader.java 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<?> loadClass(String name) { try { return (Class<?>) urlClassLoader.loadClass(name); } catch (Exception e) { } return null; }
Tags (comma-separated)
Save Edits
Cancel