Java:如何“重新启动"静态类? [英] Java: how to "restart" a static class?
问题描述
我有一个静态类(Foo)和一个主类(Main)
I have a static class (Foo) and a main class (Main)
请参阅Main.java:
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
}
}
请参阅Foo.java:
See Foo.java:
public class Foo {
public static int i = 0;
}
有什么方法可以重新启动或重置静态类?
Is there any way to restart or reset a static class?
注意:我需要这样做是因为我正在用jUnit测试静态类,并且需要在第二次测试之前清除参数.
Note: I need this because I'm testing a static class with jUnit and I need to clean parameters before second test.
编辑
ALMOST解决方案:
使用StanMax答案,我可以这样做:
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;
}
@Override
protected void finalize() throws Throwable {
System.out.println("MyClassLoader - End.");
}
}
Foo.java
public class Foo {
public static int i = 0;
static {
System.out.println("Foo - BEGIN ---------------------------------");
}
public void finalize() throws Throwable {
System.out.println("Foo - End.");
}
}
输出
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.
问题:,如果我在下面进行投射:
PROBLEM: if I do the cast bellow:
Foo foo = (Foo) fooClass.newInstance();
我收到错误消息:
java.lang.ClassCastException
推荐答案
仅当您可以卸载类时,才重新加载它,因为在加载类时将执行类静态代码.
Only if you can unload class, get it re-loaded, as class static code gets executed when class is loaded.
但是您可以直接修改值:
But you can just directly modify the value:
Foo.i = 0;
(或创建等效的方法,尤其是在静态成员不是公共成员的情况下)
(or create equivalent method for doing it, esp. if static member is not public)
这篇关于Java:如何“重新启动"静态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!