4

这是我的代码。我将 null 设置为这个引用,然后为什么它打印not null set

测试.java

try
  {                
     new Test().setNull();
     System.out.println("not null set");
   }
catch (Exception e)
  {//Catch exception if any
     System.err.println("Error: " + e.getMessage());
  }

  }
  public  void setNull()
  {
     setNull(this);
  }
  public  void setNull(Object thisRef)
  {
      thisRef = null;
  }

输出:非空集

4

4 回答 4

11

Java 不是引用调用。Java 不是引用调用。Java不是..

分配给局部变量不会更改调用者提供的任何参数曾经。

因此,该函数“什么都不做”:它分配null给一个局部变量(这也是一个参数)并返回。

于 2012-11-21T06:06:51.243 回答
4

设置一个引用null不会抛出NPE,否则想想你会如何取消你的references? 此外,当您分配null给任何引用时,只有该引用与它所指向的对象分离。但其余的参考资料仍然存在。

例如: -

MyClass obj1 = new MyClass();
MyClass obj2 = obj1; 

obj1 = null;  // only obj1 is detached from object
System.out.println(obj2);  // obj2 still points to original object

所以,当你调用你的方法时: -

new Test().setNull();

引用的副本存储在this (Java不是按引用传递,而是按值传递引用中,然后再次将其传递给另一个方法,因此再制作一个副本,然后将其设置为 null。但是原始引用仍然指向该对象。

只有当您尝试在引用上调用任何方法或访问任何对象属性时,才会抛出 NPE null

于 2012-11-21T06:05:42.057 回答
1
  1. 您的代码不完整。下次请发布一个最小的工作示例。

  2. this作为参数传递给setNull(). 请记住,参数在 Java 中是按值传递的。thisRef被初始化为指向与 this 相同的实例,但是当您重新分配null给时thisRef, 的值this保持不变。

于 2012-11-21T06:08:08.413 回答
1

对您自己的示例的另一种解释:

package com.test;

public class Test {

    public void setNull() {
        System.out.println("Before setting null : "+ this);
        System.out.println("Going to set null");
        this.setNull(this);
        System.out.println("'this' after setting null in caller method : "+this);

        this.print();// make sure that 'this' is not null;
    }

    public void print()
    {
        System.out.println("Another method");
    }

    public void setNull(Object thisRef) {
        // here you are referring the 'this' object via a variable 'thisRef'
        System.out.println("Inside setNull");
        System.out.println("thisRef value : " + thisRef); // same as 'this'
        // nullifying the 'thisRef'
        thisRef = null;
        System.out.println("thisRef after nullifying : "+thisRef);// ofcourse 'thisRef' is null
        System.out.println("'this' after setting null in method : "+this); // here the 'this' object will not be null
    }

    public static void main(String[] args) {
        new Test().setNull();
    }
}

和控制台输出:

Before setting null : com.test.Test@3e25a5
Going to set null
Inside setNull
thisRef value : com.test.Test@3e25a5
thisRef after nullifying : null
'this' after setting null in method : com.test.Test@3e25a5
'this' after setting null in caller method : com.test.Test@3e25a5
Another method
于 2012-11-21T06:39:57.110 回答