Interface 可以用作 Coherence Cache 中的键吗?

Can Interface be used as key in Coherence Cache?

我有两种不同类型的钥匙:

interface Key extends Serializable {
   String getName();
}

class KeyA implements Key {
    private String name;
    private int fieldA;
}

class KeyB implements Key {
    private String name;
    private int fieldB;
}

我可以使用 Key 接口作为 Coherence 分区缓存中的键吗?

实现该接口的 class 实例可用作此处的键。

是的,但您必须确保 Key 的所有可能实现都满足以下先决条件(来自 Oracle Documentation):

Cache keys must also provide an implementation of the hashCode() and equals() methods, and those methods must return consistent results across cluster nodes. This implies that the implementation of hashCode() and equals() must be based solely on the object's serializable state (that is, the object's nontransient fields).

...

Some cache implementations (specifically the partitioned cache) use the serialized form of the key objects for equality testing, which means that keys for which the equals() method returns true must serialize identically.

帕特里克·佩拉尔塔 (Patrick Peralta) 很好地 article 解释了这种行为。