在Clojure中,序列化这个Java对象的正确方法是什么?

6

我有一个虚拟的Java程序,我想用Clojure编写它。它有一个实现Serializable接口的类和一个保存它的函数。由于我从未在Clojure中编写过这样的程序,我想知道正确的方法是什么,你会使用哪些Clojure数据结构和API调用来解决这个问题?

import java. io. *; 

public class Box implements Serializable
{
private int width; private int height;
public void setWidth(int w)
   { width =w;}
public void setHeight(int h)
   {height = h;}
}

public static void main (String[] args)
{
   Box myBox =new Box();
  myBox.setWidth(50);
  myBox.setHeight(20) ;

try {
  FileoutputStream fs = new File("foo.ser");
  ObjectOUtputStream os = new ObjectOutputStream(fs);
  os.writeObject(myBox);
  os . close () ;

} catch (Exception ex) {} }

1个回答

9
如果你想要纯粹使用Clojure,可以使用Clojure读取器。
(代码片段如下)
示例:
user> (def box {:height 50 :width 20})
#'user/box
user> (serialize box "foo.ser")
nil
user> (deserialize "foo.ser")
{:height 50, :width 20}

这适用于大多数Clojure对象,但对于大多数Java对象而言则失败。

user> (serialize (java.util.Date.) "date.ser")
; Evaluation aborted.
No method in multimethod 'print-dup' for dispatch value: class java.util.Date

但是你可以添加方法到print-dup多方法中,以使Clojure能够以可读的方式打印其他对象。

user> (defmethod clojure.core/print-dup java.util.Date [o w]
        (.write w (str "#=(java.util.Date. " (.getTime o) ")")))
#<MultiFn clojure.lang.MultiFn@1af9e98>
user> (serialize (java.util.Date.) "date.ser")
nil
user> (deserialize "date.ser")
#<Date Mon Aug 17 11:30:00 PDT 2009>

如果您有一个具有本地Java序列化方法的Java对象,您可以直接使用它,而不必编写自己的代码来完成它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接