ImmutableMap 构建器如何创建抽象 class 的实例?

How can ImmutableMap builder create instance of abstract class?

我正在学习使用 guava 库并参考了 this 我看到使用构建器构建不可变映射的实例。 builder 构造函数如何能够创建抽象 class 实例?

   static final ImmutableMap<String, Integer> WORD_TO_INT =
       new ImmutableMap.Builder<String, Integer>()
           .put("one", 1)
           .put("two", 2)
           .put("three", 3)
           .build();

我没有,Builder 创建了一个 实现 一个 ImmutableMap (一个 class extends ImmutableMap).

为了清楚地理解,在使用 Guava 之前开始 here

更新:请参阅@Louis Wasserman 的评论。确实是一个重要的评论。

生成器 class 的 构造函数 不是 returns 不可变映射的实例。

您首先通过调用 new ImmutableMap.Builder<String, Integer>() 创建构建器,然后在此 ImmutableMap.Builder 实例上调用链中的方法 - put 方法三次,然后 build方法。

build 方法是最后调用的方法,它是创建 returns ImmutableMap 实例的方法。

这里的"trick"是ImmutableMap.Builderput方法returnsbuilder本身(最后有语句return this;)所以你可以像这样链接方法调用。

而且,事实上,build 方法 returns 是 ImmutableMap 的子 class 的实例,因为 class ImmutableMap 是抽象的,所以不能直接实例化。

ImmutableMap (Guava: Google Core Libraries for Java 21.0-SNAPSHOT API) states that it is "a Map whose contents will never change, with many other important properties detailed at ImmutableCollection".

"other important properties detailed at ImmutableCollection"包括以下保证

Each makes the following guarantees:

  • Shallow immutability. Elements can never be added, removed or replaced in this collection. This is a stronger guarantee than that of Collections.unmodifiableCollection(java.util.Collection<? extends T>), whose contents change whenever the wrapped collection is modified.
  • Null-hostility. This collection will never contain a null element.
  • Deterministic iteration. The iteration order is always well-defined, depending on how the collection was created (see the appropriate factory method for details). View collections such as Multiset.elementSet() iterate in the same order as the parent, except as noted.
  • Thread safety. It is safe to access this collection concurrently from multiple threads.
  • Integrity. This type cannot be subclassed outside this package (which would allow these guarantees to be violated).

最后的保证,完整性,暗示了这样一个事实,即 Guava 内部有 ImmutableMap 和其他不可变对象的具体实现(非抽象),这就是实际上由这些建设者返回。

另外,源码是开源的;您可以自己去了解一下 如何 构建器能够做到这一点(例如,您可以开始 here)。