4

これは私のコードです。この参照に null を設定すると、null ではないセットが出力される理由

テスト.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;
  }

出力: null セットではありません

4

4 に答える 4

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 に答える