Skip to content

Commit

Permalink
43: Keyword is now Serializable
Browse files Browse the repository at this point in the history
The case of Keyword is complicated by the fact that Keyword instances
are controlled.  We use a SerializationProxy which implements
readResolve() by calling newKeyword() so as to maintain the invariant:

    Symbol s1 = ..., s2 = ...;
    Keyword kw1 = Keyword.newKeyword(s1);
    Keyword kw2 = Keyword.newKeyword(s2);

    (s1.equals(s2)) == (kw1 == kw2)

That is, any two keywords are *identical* if and only if they were
created from any two *equal* Symbols.

Note that newKeyword(prefix, name) is exactly equivalent to
newKeyword(newSymbol(prefix, name)).
  • Loading branch information
bpsm committed Oct 25, 2015
1 parent 3cf9f7e commit 4df1383
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/main/java/us/bpsm/edn/Keyword.java
@@ -1,6 +1,11 @@
// (c) 2012 B Smith-Mannschott -- Distributed under the Eclipse Public License
package us.bpsm.edn;

import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;

import static us.bpsm.edn.Symbol.newSymbol;

/**
Expand All @@ -19,7 +24,7 @@
* k.toString() => ":foo/bar"}
* </pre>
*/
public final class Keyword implements Named, Comparable<Keyword> {
public final class Keyword implements Named, Comparable<Keyword>, Serializable {
private final Symbol sym;

/** {@inheritDoc} */
Expand Down Expand Up @@ -91,4 +96,23 @@ public int compareTo(Keyword o) {

private static final Interner<Symbol, Keyword> INTERNER = new Interner<Symbol, Keyword>();

private Object writeReplace() {
return new SerializationProxy(sym);
}

private void readObject(ObjectInputStream stream)
throws InvalidObjectException {
throw new InvalidObjectException("only proxy can be serialized");
}

private static class SerializationProxy implements Serializable {
private static final long serialVersionUID = 1L;
private final Symbol sym;
private SerializationProxy(Symbol sym) {
this.sym = sym;
}
private Object readResolve() throws ObjectStreamException {
return newKeyword(sym);
}
}
}

0 comments on commit 4df1383

Please sign in to comment.