unj*_*nj2 6 java serialization clojure
我有一个虚拟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 () ;
Run Code Online (Sandbox Code Playgroud)
} catch(Exception ex){}}
如果你想在纯Clojure中使用它,请使用Clojure阅读器.
(use 'clojure.contrib.duck-streams)
(defn serialize [o filename]
(binding [*print-dup* true]
(with-out-writer filename
(prn o))))
(defn deserialize [filename]
(read-string (slurp* filename)))
例:
user> (def box {:height 50 :width 20})
#'user/box
user> (serialize box "foo.ser")
nil
user> (deserialize "foo.ser")
{:height 50, :width 20}
Run Code Online (Sandbox Code Playgroud)
这适用于大多数Clojure对象,但大多数Java对象都失败了.
user> (serialize (java.util.Date.) "date.ser")
; Evaluation aborted.
No method in multimethod 'print-dup' for dispatch value: class java.util.Date
Run Code Online (Sandbox Code Playgroud)
但是您可以向多方法添加方法,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>
Run Code Online (Sandbox Code Playgroud)
如果你有一个带有本机Java序列化方法的Java对象,你可以使用它而不用编写自己的代码来执行它.
| 归档时间: |
|
| 查看次数: |
1261 次 |
| 最近记录: |