2011-08-29 65 views
2

這裏是我的代碼:如何將匿名類方法參數返回到原始實例化類?

public void pollLocation() 
{ 
    myLocation.getLocation(this, new LocationResult() 
    { 
     public void gotLocation(Location location) 
     { 
      //I want to assign Location object from here... 
     } 
    }); 
} 

private Location lastLocation; //...to here. 

這可能嗎?

+6

'lastLocation = something'不起作用? – Thilo

+0

我的心理調試技巧告訴我'gotLocation'是一個異步回調,但你期望它同步運行。 – SLaks

+1

@布魯諾:錯了。內部類可以寫入所有字段(而不是本地人)。他們得到了父母的「this」的參考。 – SLaks

回答

2

是。一般來說,你可以只寫

lastLocation = location 

但是,也許LocationResult類/接口也有一個叫lastLocation場。在這種情況下,你必須寫

OuterClassName.this.lastLocation = location 

但因爲它看起來像你會做一些異步輪詢,這太危險做到不同步。你也不會注意到lastLocation被設置的時候。所以最好在外部類中使用同步setter。

+0

請注意,如果每次讀取變量(即使在實例本身內)都是通過一個同步getter(它獲得與setter相同的鎖定),那麼使用同步setter將只保證線程安全 - synchronized void setX(x){...}'/'synchronized X getX(){...}')。 –

+0

是的,我不明白匿名類是在它的實例化類的範圍。我將使用Synchronized getter和setters。 – Teddy

1

你可以使用一個setter:

public void pollLocation() 
{ 
    myLocation.getLocation(this, new LocationResult() 
    { 
     public void gotLocation(Location location) 
     { 
      //I want to assign Location object from here... 
      setLastLocation(...); 
     } 
    }); 
} 

private Location lastLocation; //...to here. 
private void setLastLocation(Location l) { lastLocation = l; } 

只是要小心,多線程的問題。如果您使用多個線程,則最好聲明lastLocation volatile或使用AtomicReference。否則,您的代碼可能無法按預期工作。