通过java / scala将vector / inputstream传递给clojure函数

时间:2013-03-11 20:11:14

标签: scala clojure clojure-java-interop

我需要从java / scala调用一个clojure函数,它需要一个vector或一个inputstream作为它的第一个参数。

这样做总会产生以下异常:

执行异常[[UnsupportedOperationException:pdf(clj-pdf.main / -pdf not defined?)]]

我正在使用clj-pdf,需要调用pdf-function

(defn pdf
  "usage:
   in can be either a vector containing the document or an input stream. If in is an input stream then the forms will be read sequentially from it.
   out can be either a string, in which case it's treated as a file name, or an output stream.
   NOTE: using the :pages option will cause the complete document to reside in memory as it will need to be post processed."
  [in out]
  (if (instance? InputStream in)
    (stream-doc in out)
    (write-doc in out)))

我修改了源代码,通过

构建了一个jar
leiningen uberjar

对cjl-pdf的project.clj的修改可以在最后两行看到:

(defproject clj-pdf 
  "1.0.6"
  :description "PDF generation library"
  :url "https://github.com/yogthos/clj-pdf"
  :license {:name "GNU Lesser General Public License - v 3"
            :url "http://www.gnu.org/licenses/lgpl.html"
            :distribution :repo
            :comments "same as  iText and JFreeChart"}
  :dependencies [[org.clojure/clojure "1.5.0"]
                 [jfree/jfreechart "1.0.13"]                 
                 [itext-min "0.2"]]

  :aot [clj-pdf.main]
  :main clj-pdf.main)

在我添加的main.clj中:

(ns clj-pdf.main
  (:gen-class
   ;; neither java.io.InputStream nor ArrayList work:
   :methods [#^{:static true} [pdf [java.util.ArrayList, java.io.OutputStream] void]])
  (:use clj-pdf.core))

(defn -main [& args])

我正在使用我的scala代码中的lib,如下所示:

val output = new ByteArrayOutputStream()
val list = new java.util.ArrayList[String]
list.add( """[:list {:roman true} 
             [:chunk {:style :bold} "a bold item"] "another item" "yet another item"]
             [:phrase "some text"]                                   
             [:paragraph "yet more text"]]""")

clj_pdf.main.pdf(list, output)

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

它适用于Java:

    java.util.ArrayList a = new java.util.ArrayList();
    java.io.ByteArrayOutputStream b = new java.io.ByteArrayOutputStream();
    clj_pdf.main.pdf (a, b);

如果我添加到main.clj:

 (defn -pdf [in out] (pdf in out))

使用lein uberjar构建项目。

另一种方法是根据https://stackoverflow.com/a/6410926/151650

使用clojure.lang.RT