【问题标题】:How can anonymous class method parameters be returned to the original instantiating class?匿名类方法参数如何返回给原来的实例化类?
【发布时间】:2011-08-29 02:59:05
【问题描述】:

这是我的代码:

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.

这可能吗?

【问题讨论】:

  • lastLocation = something 不起作用?
  • 我的心理调试技能告诉我gotLocation 是一个异步回调,但您希望它同步运行。
  • @Bruno:错了。内部类可以写入所有字段(与本地相反)。他们得到了对父母this的引用。

标签: java class anonymous-class


【解决方案1】:

是的。一般来说,你可以写

lastLocation = location

但也许 LocationResult 类/接口也有一个名为 lastLocation 的字段。在这种情况下,您必须编写

OuterClassName.this.lastLocation = location

但是因为看起来你会做一些异步轮询,所以在没有同步的情况下这样做太危险了。此外,您不会注意到 lastLocation 何时设置。所以最好在外部类中使用同步设置器。

【讨论】:

  • 请注意,如果变量的每次读取(甚至在实例本身内部)都是通过同步 getter(获取与 setter 相同的锁 - - synchronized void setX(x) {...} / synchronized X getX() {...} 就是这种情况。
  • 是的,我不明白匿名类在其实例化类的范围内。我也将使用同步的 getter 和 setter。
【解决方案2】:

你可以使用 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。否则,您的代码可能无法按预期工作。

【讨论】:

    【解决方案3】:

    将 lastLocation 设为最终的 java.util.concurrent.atomic.AtomicReference 并将其设置为您心中的内容。

    (编辑:你确定一个简单的分配不起作用?它看起来在 Eclipse 中有效......)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      • 2019-09-05
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      相关资源
      最近更新 更多