How can anonymous class method parameters be returned to the original instantiating class?
Here's my code:
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.
Is this possible?
Yes. Generally you can just write
lastLocation = location
But maybe the LocationResult class/interface also has a field named lastLocation. In this case you have to write
OuterClassName.this.lastLocation = location
But since it looks like you would do some asynchronous polling, it's too dangerous to do this without synchronization. Also you wouldn't notice when the lastLocation gets set. So it's better to use a synchronized setter in the outer class.
You could use a 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; }
Just be careful about multithreading issues. If you are using multiple threads, you'd better declare lastLocation volatile
or use an AtomicReference
. Otherwise, your code might not work as you expect.
Make lastLocation a final java.util.concurrent.atomic.AtomicReference and set it to your heart's content.
(Edit: you sure a simple assignment doesn't work? It looks like that works in Eclipse ...)
精彩评论