如何在 Clojure 中创建自定义 java 对象类的数组?
这是我的代码。我想制作一个 Fruit 数组(自定义 java 对象类)。
(defn build-fruit
[part]
(let [name (:name part)
color (:color part)
price (:price part)
is_available (:is_available part)]
(-> (Fruit/newBuilder)
(.setName name)
(.setColor color)
(.setPrice price)
(.setIsAvailable is_available)
(.build))))
(defn build-fruits
[result length]
(loop [remaining-fruits result
final-fruits (make-array Fruit length)]
(if (empty? remaining-fruits)
final-fruits
(let [[part & remaining] remaining-fruits]
(recur remaining
(into-array final-fruits (build-fruit part)))))) ;got an error here
)
(defn -getAllFruits [this ^Empty req ^StreamObserver res]
(let [result (clj-grpc.database/findAllFruit)
length (count result)
fruits (build-fruits result length)]
(doto res
(.onNext (-> (ListOfFruits/newBuilder)
(.addAllFruit fruits)
(.build)))
(.onCompleted))))
但出现错误
java.lang.ClassCastException: [Lorg.example.fruitproto.Fruit; cannot be cast to java.lang.Class
at clojure.core$into_array.invokeStatic(core.clj:3431)
at clojure.core$into_array.invoke(core.clj:3431)
at clj_grpc.fruitservice$build_fruits.invokeStatic(fruitservice.clj:118)
at clj_grpc.fruitservice$build_fruits.invoke(fruitservice.clj:110)
我的猜测是我无法使用 make-array
。我也不能使用像这样的简单数组 []
因为它还出现了另一个错误。实现这一目标的正确方法是什么?
This is my code. I would like to make an array of Fruit (an custom java object class).
(defn build-fruit
[part]
(let [name (:name part)
color (:color part)
price (:price part)
is_available (:is_available part)]
(-> (Fruit/newBuilder)
(.setName name)
(.setColor color)
(.setPrice price)
(.setIsAvailable is_available)
(.build))))
(defn build-fruits
[result length]
(loop [remaining-fruits result
final-fruits (make-array Fruit length)]
(if (empty? remaining-fruits)
final-fruits
(let [[part & remaining] remaining-fruits]
(recur remaining
(into-array final-fruits (build-fruit part)))))) ;got an error here
)
(defn -getAllFruits [this ^Empty req ^StreamObserver res]
(let [result (clj-grpc.database/findAllFruit)
length (count result)
fruits (build-fruits result length)]
(doto res
(.onNext (-> (ListOfFruits/newBuilder)
(.addAllFruit fruits)
(.build)))
(.onCompleted))))
But got an error
java.lang.ClassCastException: [Lorg.example.fruitproto.Fruit; cannot be cast to java.lang.Class
at clojure.core$into_array.invokeStatic(core.clj:3431)
at clojure.core$into_array.invoke(core.clj:3431)
at clj_grpc.fruitservice$build_fruits.invokeStatic(fruitservice.clj:118)
at clj_grpc.fruitservice$build_fruits.invoke(fruitservice.clj:110)
My guess is I cann't use make-array
. I also can't use simple array like this []
because it also got another error. What is the proper way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
下面是一个使用
into-array
的独立示例,构建LocalDate
而不是Fruit
的数组:Here is a standalone example of using
into-array
, building an array ofLocalDate
rather thanFruit
: