是否可以将类中的类的实例设置为null

时间:2013-06-04 17:39:07

标签: java garbage-collection

是否可以将类中的类的实例设置为null。例如,我可以做这样的事吗

int main{
    //Create a new test object
    Test test = new Test();
    //Delete that object. This method should set the object "test" to null, 
    //thus allowing it to be called by the garbage collector.
    test.delete();

}


public class Test{

    public delete(){
        this = null;
    }
}

我试过这个并没有用。使用" this = null"我得到左侧需要变量的错误。有没有办法实现类似的东西?

5 个答案:

答案 0 :(得分:7)

对象的实例不知道哪些引用可能引用它,因此对象中的代码无法使这些引用为空。你要求的是不可能的(*)。

* 至少没有添加一堆脚手架以跟踪所有引用,并以某种方式告知其所有者它们应该被取消 - 绝不会是“为了方便”。

答案 1 :(得分:4)

你可以做这样的事情

public class WrappedTest {
    private Test test;
    public Test getTest() { return test; }
    public void setTest(Test test) { this.test = test; }
    public void delete() { test = null; }
}

答案 2 :(得分:0)

this”是最终变量。你不能为它指定任何值。

如果要设置引用null,可以执行此操作

test = null;

答案 3 :(得分:0)

this是对您班级实例的引用。修改引用变量时,它只修改 引用和 nothing else。例如:

Integer a = new Integer(1);
Integer b = a;

a = new Integer(2);      //does NOT modify variable b

System.out.println(b);   //prints 1

答案 4 :(得分:0)

Is it possible to set to null an instance of a class within the class?.

您无法从同一实例的成员方法执行此操作。所以,this=null或那种东西是行不通的。

为什么将实例设置为null?

这个问题本身是错误的,我们设置引用null而不是实例。未使用的对象会自动在java中收集垃圾。

如果设置test=null,它最终会被垃圾收集。

 int main{
    //Create a new test object
    Test test = new Test();
    // use the object through test
    test=null;
}
相关问题