开发者

Returning an anonymous class that uses a final primitive. How does it work?

开发者 https://www.devze.com 2022-12-28 10:59 出处:网络
I was wondering if someone could explain how the following code works: public interface Result { public int getCount();

I was wondering if someone could explain how the following code works:

public interface Result {
  public int getCount();
  public List<Thing> getThings();
}


class SomeClass {
...
  public Result getThingResult() {
    final List<Thing> things = .. populated from something.

    final int count = 5;

    return new Result {
      @Override
      public int getCount() {
        return count;
      }

      @Override
      public List<Thing> getThings();
        return things;
      }
    }
  }
..开发者_JAVA百科.
}

Where do the primitive int , List reference and List instance get stored in memory? It can't be on the stack.. so where? Is there a difference between how references and primitives are handled in this situation?

Thanks a bunch, Tim P.


The used final locals (and any outer this references) are copied to synthetic fields of the inner class during construction. References and primitives are, as always, treated the same. Both are (shallow) copied.

You can use javap from the JDK to see what is being generated.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号