[英]Problems calling a clojure function that takes a map as parameter from java
我正在使用带有几个模块的 maven,一个在 java 中,另一个在 clojure 中。 我正在从 java 调用一个 clojure 函数,并希望传入一个 HashMap 作为参数并返回一个 HashMap。 (我在 clojure 项目上运行了 lein uberjar 和 lein pom 以使其与 maven 一起工作。我可以使用简单类型(例如 String)为 clojure 函数工作,因此 maven 设置确实有效。)
当我运行一些调用 java 代码的 java 单元测试时出现以下错误:
java.lang.ClassCastException: class clojure.lang.LazySeq cannot be cast to class java.util.Map (clojure.lang.LazySeq is in unnamed module o
f loader 'app'; java.util.Map is in module java.base of loader 'bootstrap')
我怎样才能让它工作? 这是从java调用clojure方法的正确方法吗? 如果 HashMap 将 POJO 对象作为值而不是字符串呢?
我的java代码:
import interop.Core;
public class BillingCalc {
static Map<String, String> nonEmptyItems(Map<String, String> items) {
return Core.non_empty_seats(new HashMap<String, String>());
}
}
我的clojure代码:
(ns interop.core
(:gen-class
:name interop.Core
:methods [^{:static true} [apply_vat_to_netto [java.math.BigDecimal java.math.BigDecimal] java.math.BigDecimal]
^{:static true} [non_empty_seats [java.util.Map] java.util.Map]]) )
(defn -filter-empty-seats
"filter out those with empty seats"
[seats]
(filter (fn [[_ v]] (pos? (:booked-items v))) seats))
(defn -non_empty_seats
[java-seats]
(-filter-empty-seats (into {} java-seats)))
我猜你的错误是由:gen-class
中的这个定义引起的:
[non_empty_seats [java.util.Map] java.util.Map]]
来自:gen-class 的文档:
:methods [ [name [param-types] return-type], ...]
返回值的预期类型是java.util.Map
,但-filter-empty-seats
中的filter
返回clojure.lang.LazySeq
的实例。 您应该像这样重写-non_empty_seats
:
(defn -non_empty_seats
[java-seats]
(into {} (-filter-empty-seats java-seats)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.