【问题标题】:Returning Vectors, Sequences and Maps from Clojure to Java将向量、序列和映射从 Clojure 返回到 Java
【发布时间】:2014-11-20 22:00:14
【问题描述】:

我已经阅读了对 Calling clojure from java 的出色回答,它展示了从 Java 调用 Clojure 的新风格。

但是给出的例子只是返回一个浮点数。如何将 Clojure 向量和其他序列类型从 Clojure 返回到 Java?还有地图?

特别是在这个 gen-class 中:

(ns dummy-app.core
  (:gen-class
   :name com.example.dummy
   :methods [#^{:static true} [f [int] int]
             #^{:static true} [getVect [] XXXX]
             #^{:static true} [getMap [] YYYY]
             #^{:static true} [getSeq [] ZZZZ]
             ] ))

我应该为 XXXX、YYYY 和 ZZZZ 输入什么?在我的 Java 程序中它们应该是什么类型?

更新:作为对 Tomo 有希望的回答的回应,如果我尝试在 gen-clas 中使用 IPersistentVector,我会得到 ​​p>

Caused by: java.lang.ClassNotFoundException: java.lang.IPersistentVector

当我尝试创建 Uberjar 时。我想我还需要做其他事情来导入这些类型?

更新 2:好的,感谢 Tomo 提供的更多 cmets,这似乎可行:

(ns dummy-app.core
  (import clojure.lang.IPersistentVector)
  (:gen-class
   :name com.example.dummy
   :methods [#^{:static true} [f [int] int]
             #^{:static true} [getVect [] clojure.lang.IPersistentVector]
             ] ))

【问题讨论】:

    标签: java clojure interop


    【解决方案1】:

    我会使用适当的接口:IPersistentMapIPersistentVectorISeq 等等。查看源代码 (https://github.com/clojure/clojure/tree/master/src/jvm/clojure/lang)。

    【讨论】:

    • 谢谢。但仍然不适合我。我用额外的细节更新了问题。
    • 好吧,我猜你需要在 ns 宏上使用 :import 子句导入适当的 Java 类,对吧?
    【解决方案2】:

    您也可以只指定适当的 Java 接口。

    Clojure 向量、列表和序列都实现了java.util.List

    Clojure 映射实现java.util.Map

    函数同时实现java.util.concurrent.Callablejava.lang.Runnable

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      相关资源
      最近更新 更多