Java 是否可以将类中的类实例设置为null
是否可以将类中的类实例设置为null。例如,我可以做这样的事情吗Java 是否可以将类中的类实例设置为null,java,garbage-collection,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.
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;
}
}
public class WrappedTest {
private Test test;
public Test getTest() { return test; }
public void setTest(Test test) { this.test = test; }
public void delete() { test = null; }
}
我试过这个,但它不起作用。使用“this=null”我得到一个错误,左侧需要是一个变量。有没有办法实现类似的目标 “此
”是最终变量。不能为其指定任何值
如果要将引用设置为null,可以这样做
test = 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;
}
}
public class WrappedTest {
private Test test;
public Test getTest() { return test; }
public void setTest(Test test) { this.test = test; }
public void delete() { test = null; }
}
对象的实例不知道哪些引用可能引用它,因此对象中的代码不可能使这些引用为空。你所要求的是不可能的(*)
*至少,如果不添加一堆脚手架来跟踪所有引用,并以某种方式通知它们的所有者它们应该为空,这绝不是“为了方便”。
这是对类实例的引用。修改引用变量时,它只修改该引用,而不修改其他内容。例如:
Integer a = new Integer(1);
Integer b = a;
a = new Integer(2); //does NOT modify variable b
System.out.println(b); //prints 1
是否可以将类中的类实例设置为null?
不能从同一实例的成员方法执行此操作。所以,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;
}
是的,但有没有一种方法可以达到相同的结果?有什么理由要将其设置为null吗?垃圾收集器很聪明。他们知道什么时候再也够不到一个对象了。您正在尝试删除对此对象的所有引用吗?您正在尝试“销毁”该对象。在对象的所有引用消失之前,无法执行此操作。您最好在对象中放置一个“已删除”标志,这会导致对该对象的所有调用失败。@rioneye,问题是为什么要将其设置为null。实例中的对象属于该实例。该实例(如果不是根实例)及其状态符合收集条件。你的故事还有别的吗?通常不需要将对象引用设置为null。@rioneye一旦该方法退出,如果该对象仅由局部变量引用,则该对象将符合GC的条件。“而不是使用多行代码删除类内的所有引用并将对象本身设置为null”-这可能是您的混淆点。99.9%的引用没有显式为null。相反,它们以这样或那样的方式“消失”——包含的对象是GCed,包含的方法存在,等等。只有在少数情况下(例如,一个大的引用数组,其中对象可能被“丢弃”,但仍然从数组中引用),您才需要显式地为任何对象设置null。这假设只有一个对象实例,但是谢谢你的想法。@rioneye你会为你想删除的每个测试实例化一个新的WrappedTest
实例test
是一个实例变量,而不是静态变量,因此每个WrappedTest
都有自己的test