匿名类方法参数如何返回到原来的实例化类?
这是我的代码:
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.
这可能吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。一般来说,您可以只写
但也许 LocationResult 类/接口也有一个名为 lastLocation 的字段。在这种情况下,您必须编写
But 由于看起来您会执行一些异步轮询,因此在没有同步的情况下执行此操作太危险了。此外,您也不会注意到 LastLocation 何时被设置。所以最好在外部类中使用同步setter。
Yes. Generally you can just write
But maybe the LocationResult class/interface also has a field named lastLocation. In this case you have to write
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.
您可以使用设置器:
只需小心多线程问题。如果您使用多个线程,最好声明lastLocation
volatile
或使用AtomicReference
。否则,您的代码可能无法按您的预期工作。You could use a setter:
Just be careful about multithreading issues. If you are using multiple threads, you'd better declare lastLocation
volatile
or use anAtomicReference
. Otherwise, your code might not work as you expect.将lastLocation设置为最终的 java.util.concurrent .atomic.AtomicReference 并将其设置为您喜欢的内容。
(编辑:您确定简单的分配不起作用吗?看起来在 Eclipse 中可以起作用......)
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 ...)