我創建一個示例演示程序讓我說,我怎麼能解除分配靜態變量的引用,在Java方法使用垃圾收集明白了嗎?垃圾收集器在java中的靜態變量或方法上工作嗎?
我使用弱引用未能阻止垃圾收集器。
類Sample
public class Sample {
private static String userName;
private static String password;
static {
userName = "GAURAV";
password = "password";
}
public static String getUserName(){
return userName;
}
public static String getPassword(){
return password;
}
}
類User
import java.lang.ref.WeakReference;
public class User {
public static void main(String[] args) {
/**
* Created one object of Sample class
*/
Sample obj1 = new Sample();
/**
* I can also access the value of userName through it's class name
*/
System.out.println(obj1.getUserName()); //GAURAV
WeakReference<Sample> wr = new WeakReference<Sample>(obj1);
System.out.println(wr.get()); //[email protected]
obj1 = null;
System.gc();
System.out.println(wr.get()); // null
/**
* I have deallocate the Sample object . No more object referencing the Sample oblect class but I am getting the value of static variable.
*/
System.out.println(Sample.getUserName()); // GAURAV
}
}
垃圾收集器收集的對象,而不是變量。變量是包含/引用的容器。最重要的是,在大多數情況下,你不想亂搞垃圾收集。 – ignis
靜態過多。你爲什麼要混合它們? –
不,你必須自己清理 – Nactus