访问可变的 java.util.List 在 Clojure 中

huangapple go评论61阅读模式
英文:

Access mutable java.util.List in Clojure

问题

我正在使用一个第三方的Java库,其中一个库事件将java.util.List作为参数传递,而Clojure将其公开为clojure.lang.APersistentVector。我遇到的问题是,该库要求我对该列表进行修改以实现我想要的功能。然而,由于Clojure将列表返回为APersistentVector,所有可变方法都会抛出UnsupportedOperationException异常。

是否有可能强制Clojure使用可变的Java List 实现,而不是不可变的Clojure版本?

我知道这与Clojure的风格很不符,但这是库的工作方式,现在我只想让事情能够运行起来。

谢谢,

Paul

英文:

I'm working with a 3rd party Java library, one of the library events passes a java.util.List as a parameter which Clojure exposes as a clojure.lang.APersistentVector. The problem I'm having is that the library requires that I mutate that list to achieve the functionality I am after. However, as Clojure has returned the list as APersistentVector all the mutable methods throw an UnsupportedOperationException.

Is it possible to force Clojure to work with a mutable Java implementation of List rather than the un-mutable Clojure version?

I appreciate that this is very un-Clojure like but its the way the Library works and for now, I just want to get things working.

Thanks,

Paul

答案1

得分: 0

这不清楚你所说的"which Clojure exposes as a clojure.lang.APersistentVector"是什么意思。如果Clojure调用一个返回具有类java.util.ArrayList的对象x的Java方法,那么在Clojure中调用(class x)应该显示java.util.ArrayList。

也许在您使用的库中有一些转换代码,可能是Java方法调用的Clojure包装器,正在进行这种转换?

以下是一个示例,展示了在Clojure代码中如何获取java.util.ArrayList对象并对其进行修改:

(def mutlist1 (java.util.ArrayList. [1 2 3]))
mutlist1 ; => [1 2 3]
(class mutlist1) ; => java.util.ArrayList
;; 在索引1处添加新元素-1
(.add mutlist1 1 -1)
mutlist1 ; => [1 -1 2 3]
英文:

It isn't clear what you mean when you say "which Clojure exposes as a clojure.lang.APersistentVector". If Clojure calls a Java method that returns an object x with class java.util.ArrayList, then calling (class x) in Clojure should show java.util.ArrayList.

Is there perhaps some conversion code happening in the library you are using, perhaps a Clojure wrapper for the Java method call(s), that is doing this conversion?

Example of Clojure REPL session showing you can indeed get java.util.ArrayList objects and mutate them in Clojure code:

user=> (def mutlist1 (java.util.ArrayList. [1 2 3]))
#'user/mutlist1
user=> mutlist1
[1 2 3]
user=> (class mutlist1)
java.util.ArrayList
;; add a new element -1 at index 1
user=> (.add mutlist1 1 -1)
nil
user=> mutlist1
[1 -1 2 3]

huangapple
  • 本文由 发表于 2020年9月16日 01:17:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63906889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定