如何通过gen-class在Clojure中生成可序列化的java类?

时间:2013-02-25 07:40:39

标签: serialization clojure clojure-java-interop gen-class

我们需要通过Java Serialization机制将Clojure生成的一堆Java对象序列化为一个文件。

(gen-class
 :name lancelot.Instance
 :extends cc.mallet.types.Instance)

(gen-class
 :name lancelot.FilterPipe
 :extends cc.mallet.pipe.Pipe
 :prefix "-filter-"
 :methods [[pipe [cc.mallet.types.Instance] lancelot.Instance]])

(defn -filter-pipe [this ^cc.mallet.types.Instance inst]
  (.setData inst (clojure.string/join " "
    (filter normal-word? (clojure.string/split (.getData inst) #"\s+"))))
  inst)

(gen-class
 :name lancelot.SegmentorPipe
 :extends cc.mallet.pipe.Pipe
 :prefix "-segmentor-"
 :methods [[pipe [cc.mallet.types.Instance] lancelot.Instance]])

(defn -segmentor-pipe [this ^cc.mallet.types.Instance inst]
  (.setData inst (seg/seg (.getData inst)))
  inst)

如上所述,lancelot.FilterPipe和lancelot.SegmentorPipe的实例需要序列化。我们发现编写对象流是可以的,但是在重新编译代码之后读取对象流是行不通的。

  

线程“Thread-8”中的异常java.io.InvalidClassException:   lancelot.SegmentorPipe;本地类不兼容:stream classdesc   serialVersionUID = 2583852145887230781,本地类serialVersionUID =   在java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:579)处的-2255006751011717591   java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1601)     在   java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)     在   java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1750)     在java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)     在java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)

由于serialVersionUID是静态的和final的,但似乎gen-class只能生成实例级的final字段。所以问题是我无法为生成的类设置特定的serialVersionUID。

对此问题有何建议?提前谢谢。

1 个答案:

答案 0 :(得分:0)

请尝试添加Serializable

(gen-class :name lancelot.Instance :implements [java.io.Serializable] :extends cc.mallet.types.Instance)