2011-08-29 64 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。否则,您的代码可能无法按预期工作。