簡體   English   中英

如何綁定兩個對象的引用?

[英]How to bind references of two objects?

如果我有2個物件

Foo foo;
Foo bar = foo;

它們最初都指向null。

如果foo get已初始化

foo = new Foo();

bar引用null,但我希望將其綁定到foo。

因此,foo引用的每次更改都會使bar引用保持相同。

有沒有一種方法可以讓bar自動指向與foo相同的地址,

即使更改,還是必須手動調用?

foo = new Foo();
bar = foo;

foobar都不是真正的對象,而是對對象的引用。

在初始聲明中,將兩者都設置為undefined,或更准確地說, fooundefined ,並且將bar設置為相同的值。 但是,即使您已初始化foo ,答案也將是相同的。

當將foo的值設置為新對象( new Foo )時, bar仍未定義。

所以答案是,是的,您必須手動進行。

您可以通過創建類似指針類的方法來使用變通方法。

class Pointer <T> {
  T target = null;
  Pointer(T target){
    this.target = target;
  }
  static Pointer nullPointer(){
    return new Pointer(null);
  }
  public void setTarget(T target){
    this.target = target;
  }
  public T getTarget(){
    return target;
  }
}

您可以像這樣使用它:

Pointer<Foo> foo = Pointer.nullPointer(); //target=null
Pointer<Foo> bar = foo;           //bar now also "points" to null
foo.setTarget(new Foo()); //now BOTH have the new object as the target

Java是按值傳遞,而不是按引用傳遞。 bar的引用不應與foo的引用相同

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM