在 Immutables 中执行特定的 Map 实现

Enforce specific Map implementation in Immutables

我正在使用 Immutables Java 库,如何在不必使用特定参考的情况下强制实施特定地图?

@Immutable
public interface ConfigIF {
  Map<String, String> getOptions();
}

如果我使用上面的代码,具体 MapLinkedHashMap.

@Immutable
public interface ConfigIF {
  TreeMap<String, String> getOptions();
}

如果我使用上面的代码,参考和实现都是 TreeMap

有没有一种方法可以将 Map 指定为参考,但强制将 TreeMap 作为具体类型?

绝对不是——而且应该被禁止(即:作为用户,您没有任何选项可以改变它)。这不是特定于您的库,而是一般来说 return 是 Map 而不是 TreeMap 的任何代码。

换个角度看,如果您 return 一个 Map 用户不希望在其上调用 ceilingEntry(在 TreeMap 中可用,但不在 Map) 通过引用的转换。

java-8 在通过 Collectors.toXXX 时做同样的事情。例如 Collectors.toList 明确表示:

There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned.

这意味着他们可以return他们认为最合适的任何东西。